div.rs

   1use crate::{
   2    point, px, Action, AnyDrag, AnyElement, AnyTooltip, AnyView, AppContext, BorrowAppContext,
   3    BorrowWindow, Bounds, ClickEvent, DispatchPhase, Element, ElementId, FocusHandle, IntoElement,
   4    KeyContext, KeyDownEvent, KeyUpEvent, LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent,
   5    MouseUpEvent, ParentElement, Pixels, Point, Render, ScrollWheelEvent, SharedString, Size,
   6    StackingOrder, Style, StyleRefinement, Styled, Task, View, Visibility, WindowContext,
   7};
   8
   9use collections::HashMap;
  10use refineable::Refineable;
  11use smallvec::SmallVec;
  12use std::{
  13    any::{Any, TypeId},
  14    cell::RefCell,
  15    cmp::Ordering,
  16    fmt::Debug,
  17    marker::PhantomData,
  18    mem,
  19    rc::Rc,
  20    time::Duration,
  21};
  22use taffy::style::Overflow;
  23use util::ResultExt;
  24
  25const DRAG_THRESHOLD: f64 = 2.;
  26const TOOLTIP_DELAY: Duration = Duration::from_millis(500);
  27
  28pub struct GroupStyle {
  29    pub group: SharedString,
  30    pub style: Box<StyleRefinement>,
  31}
  32
  33pub struct DragMoveEvent<T> {
  34    pub event: MouseMoveEvent,
  35    pub bounds: Bounds<Pixels>,
  36    drag: PhantomData<T>,
  37}
  38
  39impl<T: 'static> DragMoveEvent<T> {
  40    pub fn drag<'b>(&self, cx: &'b AppContext) -> &'b T {
  41        cx.active_drag
  42            .as_ref()
  43            .and_then(|drag| drag.value.downcast_ref::<T>())
  44            .expect("DragMoveEvent is only valid when the stored active drag is of the same type.")
  45    }
  46}
  47
  48impl Interactivity {
  49    pub fn on_mouse_down(
  50        &mut self,
  51        button: MouseButton,
  52        listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
  53    ) {
  54        self.mouse_down_listeners
  55            .push(Box::new(move |event, bounds, phase, cx| {
  56                if phase == DispatchPhase::Bubble
  57                    && event.button == button
  58                    && bounds.visibly_contains(&event.position, cx)
  59                {
  60                    (listener)(event, cx)
  61                }
  62            }));
  63    }
  64
  65    pub fn capture_any_mouse_down(
  66        &mut self,
  67        listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
  68    ) {
  69        self.mouse_down_listeners
  70            .push(Box::new(move |event, bounds, phase, cx| {
  71                if phase == DispatchPhase::Capture && bounds.visibly_contains(&event.position, cx) {
  72                    (listener)(event, cx)
  73                }
  74            }));
  75    }
  76
  77    pub fn on_any_mouse_down(
  78        &mut self,
  79        listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
  80    ) {
  81        self.mouse_down_listeners
  82            .push(Box::new(move |event, bounds, phase, cx| {
  83                if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) {
  84                    (listener)(event, cx)
  85                }
  86            }));
  87    }
  88
  89    pub fn on_mouse_up(
  90        &mut self,
  91        button: MouseButton,
  92        listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
  93    ) {
  94        self.mouse_up_listeners
  95            .push(Box::new(move |event, bounds, phase, cx| {
  96                if phase == DispatchPhase::Bubble
  97                    && event.button == button
  98                    && bounds.visibly_contains(&event.position, cx)
  99                {
 100                    (listener)(event, cx)
 101                }
 102            }));
 103    }
 104
 105    pub fn capture_any_mouse_up(
 106        &mut self,
 107        listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
 108    ) {
 109        self.mouse_up_listeners
 110            .push(Box::new(move |event, bounds, phase, cx| {
 111                if phase == DispatchPhase::Capture && bounds.visibly_contains(&event.position, cx) {
 112                    (listener)(event, cx)
 113                }
 114            }));
 115    }
 116
 117    pub fn on_any_mouse_up(
 118        &mut self,
 119        listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
 120    ) {
 121        self.mouse_up_listeners
 122            .push(Box::new(move |event, bounds, phase, cx| {
 123                if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) {
 124                    (listener)(event, cx)
 125                }
 126            }));
 127    }
 128
 129    pub fn on_mouse_down_out(
 130        &mut self,
 131        listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
 132    ) {
 133        self.mouse_down_listeners
 134            .push(Box::new(move |event, bounds, phase, cx| {
 135                if phase == DispatchPhase::Capture && !bounds.visibly_contains(&event.position, cx)
 136                {
 137                    (listener)(event, cx)
 138                }
 139            }));
 140    }
 141
 142    pub fn on_mouse_up_out(
 143        &mut self,
 144        button: MouseButton,
 145        listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
 146    ) {
 147        self.mouse_up_listeners
 148            .push(Box::new(move |event, bounds, phase, cx| {
 149                if phase == DispatchPhase::Capture
 150                    && event.button == button
 151                    && !bounds.visibly_contains(&event.position, cx)
 152                {
 153                    (listener)(event, cx);
 154                }
 155            }));
 156    }
 157
 158    pub fn on_mouse_move(
 159        &mut self,
 160        listener: impl Fn(&MouseMoveEvent, &mut WindowContext) + 'static,
 161    ) {
 162        self.mouse_move_listeners
 163            .push(Box::new(move |event, bounds, phase, cx| {
 164                if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) {
 165                    (listener)(event, cx);
 166                }
 167            }));
 168    }
 169
 170    pub fn on_drag_move<T>(
 171        &mut self,
 172        listener: impl Fn(&DragMoveEvent<T>, &mut WindowContext) + 'static,
 173    ) where
 174        T: 'static,
 175    {
 176        self.mouse_move_listeners
 177            .push(Box::new(move |event, bounds, phase, cx| {
 178                if phase == DispatchPhase::Capture {
 179                    if cx
 180                        .active_drag
 181                        .as_ref()
 182                        .is_some_and(|drag| drag.value.as_ref().type_id() == TypeId::of::<T>())
 183                    {
 184                        (listener)(
 185                            &DragMoveEvent {
 186                                event: event.clone(),
 187                                bounds: bounds.bounds,
 188                                drag: PhantomData,
 189                            },
 190                            cx,
 191                        );
 192                    }
 193                }
 194            }));
 195    }
 196
 197    pub fn on_scroll_wheel(
 198        &mut self,
 199        listener: impl Fn(&ScrollWheelEvent, &mut WindowContext) + 'static,
 200    ) {
 201        self.scroll_wheel_listeners
 202            .push(Box::new(move |event, bounds, phase, cx| {
 203                if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) {
 204                    (listener)(event, cx);
 205                }
 206            }));
 207    }
 208
 209    pub fn capture_action<A: Action>(
 210        &mut self,
 211        listener: impl Fn(&A, &mut WindowContext) + 'static,
 212    ) {
 213        self.action_listeners.push((
 214            TypeId::of::<A>(),
 215            Box::new(move |action, phase, cx| {
 216                let action = action.downcast_ref().unwrap();
 217                if phase == DispatchPhase::Capture {
 218                    (listener)(action, cx)
 219                }
 220            }),
 221        ));
 222    }
 223
 224    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut WindowContext) + 'static) {
 225        self.action_listeners.push((
 226            TypeId::of::<A>(),
 227            Box::new(move |action, phase, cx| {
 228                let action = action.downcast_ref().unwrap();
 229                if phase == DispatchPhase::Bubble {
 230                    (listener)(action, cx)
 231                }
 232            }),
 233        ));
 234    }
 235
 236    pub fn on_boxed_action(
 237        &mut self,
 238        action: &Box<dyn Action>,
 239        listener: impl Fn(&Box<dyn Action>, &mut WindowContext) + 'static,
 240    ) {
 241        let action = action.boxed_clone();
 242        self.action_listeners.push((
 243            (*action).type_id(),
 244            Box::new(move |_, phase, cx| {
 245                if phase == DispatchPhase::Bubble {
 246                    (listener)(&action, cx)
 247                }
 248            }),
 249        ));
 250    }
 251
 252    pub fn on_key_down(&mut self, listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static) {
 253        self.key_down_listeners
 254            .push(Box::new(move |event, phase, cx| {
 255                if phase == DispatchPhase::Bubble {
 256                    (listener)(event, cx)
 257                }
 258            }));
 259    }
 260
 261    pub fn capture_key_down(
 262        &mut self,
 263        listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static,
 264    ) {
 265        self.key_down_listeners
 266            .push(Box::new(move |event, phase, cx| {
 267                if phase == DispatchPhase::Capture {
 268                    listener(event, cx)
 269                }
 270            }));
 271    }
 272
 273    pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) {
 274        self.key_up_listeners
 275            .push(Box::new(move |event, phase, cx| {
 276                if phase == DispatchPhase::Bubble {
 277                    listener(event, cx)
 278                }
 279            }));
 280    }
 281
 282    pub fn capture_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) {
 283        self.key_up_listeners
 284            .push(Box::new(move |event, phase, cx| {
 285                if phase == DispatchPhase::Capture {
 286                    listener(event, cx)
 287                }
 288            }));
 289    }
 290
 291    pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut WindowContext) + 'static) {
 292        self.drop_listeners.push((
 293            TypeId::of::<T>(),
 294            Box::new(move |dragged_value, cx| {
 295                listener(dragged_value.downcast_ref().unwrap(), cx);
 296            }),
 297        ));
 298    }
 299
 300    pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut WindowContext) + 'static)
 301    where
 302        Self: Sized,
 303    {
 304        self.click_listeners
 305            .push(Box::new(move |event, cx| listener(event, cx)));
 306    }
 307
 308    pub fn on_drag<T, W>(
 309        &mut self,
 310        value: T,
 311        constructor: impl Fn(&T, &mut WindowContext) -> View<W> + 'static,
 312    ) where
 313        Self: Sized,
 314        T: 'static,
 315        W: 'static + Render,
 316    {
 317        debug_assert!(
 318            self.drag_listener.is_none(),
 319            "calling on_drag more than once on the same element is not supported"
 320        );
 321        self.drag_listener = Some((
 322            Box::new(value),
 323            Box::new(move |value, cx| constructor(value.downcast_ref().unwrap(), cx).into()),
 324        ));
 325    }
 326
 327    pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut WindowContext) + 'static)
 328    where
 329        Self: Sized,
 330    {
 331        debug_assert!(
 332            self.hover_listener.is_none(),
 333            "calling on_hover more than once on the same element is not supported"
 334        );
 335        self.hover_listener = Some(Box::new(listener));
 336    }
 337
 338    pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static)
 339    where
 340        Self: Sized,
 341    {
 342        debug_assert!(
 343            self.tooltip_builder.is_none(),
 344            "calling tooltip more than once on the same element is not supported"
 345        );
 346        self.tooltip_builder = Some(Rc::new(build_tooltip));
 347    }
 348
 349    pub fn block_mouse(&mut self) {
 350        self.block_mouse = true;
 351    }
 352}
 353
 354pub trait InteractiveElement: Sized {
 355    fn interactivity(&mut self) -> &mut Interactivity;
 356
 357    fn group(mut self, group: impl Into<SharedString>) -> Self {
 358        self.interactivity().group = Some(group.into());
 359        self
 360    }
 361
 362    fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
 363        self.interactivity().element_id = Some(id.into());
 364
 365        Stateful { element: self }
 366    }
 367
 368    fn track_focus(mut self, focus_handle: &FocusHandle) -> Focusable<Self> {
 369        self.interactivity().focusable = true;
 370        self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
 371        Focusable { element: self }
 372    }
 373
 374    fn key_context<C, E>(mut self, key_context: C) -> Self
 375    where
 376        C: TryInto<KeyContext, Error = E>,
 377        E: Debug,
 378    {
 379        if let Some(key_context) = key_context.try_into().log_err() {
 380            self.interactivity().key_context = Some(key_context);
 381        }
 382        self
 383    }
 384
 385    fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
 386        debug_assert!(
 387            self.interactivity().hover_style.is_none(),
 388            "hover style already set"
 389        );
 390        self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
 391        self
 392    }
 393
 394    fn group_hover(
 395        mut self,
 396        group_name: impl Into<SharedString>,
 397        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
 398    ) -> Self {
 399        self.interactivity().group_hover_style = Some(GroupStyle {
 400            group: group_name.into(),
 401            style: Box::new(f(StyleRefinement::default())),
 402        });
 403        self
 404    }
 405
 406    fn on_mouse_down(
 407        mut self,
 408        button: MouseButton,
 409        listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
 410    ) -> Self {
 411        self.interactivity().on_mouse_down(button, listener);
 412        self
 413    }
 414
 415    fn capture_any_mouse_down(
 416        mut self,
 417        listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
 418    ) -> Self {
 419        self.interactivity().capture_any_mouse_down(listener);
 420        self
 421    }
 422
 423    fn on_any_mouse_down(
 424        mut self,
 425        listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
 426    ) -> Self {
 427        self.interactivity().on_any_mouse_down(listener);
 428        self
 429    }
 430
 431    fn on_mouse_up(
 432        mut self,
 433        button: MouseButton,
 434        listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
 435    ) -> Self {
 436        self.interactivity().on_mouse_up(button, listener);
 437        self
 438    }
 439
 440    fn capture_any_mouse_up(
 441        mut self,
 442        listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
 443    ) -> Self {
 444        self.interactivity().capture_any_mouse_up(listener);
 445        self
 446    }
 447
 448    fn on_mouse_down_out(
 449        mut self,
 450        listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
 451    ) -> Self {
 452        self.interactivity().on_mouse_down_out(listener);
 453        self
 454    }
 455
 456    fn on_mouse_up_out(
 457        mut self,
 458        button: MouseButton,
 459        listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
 460    ) -> Self {
 461        self.interactivity().on_mouse_up_out(button, listener);
 462        self
 463    }
 464
 465    fn on_mouse_move(
 466        mut self,
 467        listener: impl Fn(&MouseMoveEvent, &mut WindowContext) + 'static,
 468    ) -> Self {
 469        self.interactivity().on_mouse_move(listener);
 470        self
 471    }
 472
 473    fn on_drag_move<T: 'static>(
 474        mut self,
 475        listener: impl Fn(&DragMoveEvent<T>, &mut WindowContext) + 'static,
 476    ) -> Self
 477    where
 478        T: 'static,
 479    {
 480        self.interactivity().on_drag_move(listener);
 481        self
 482    }
 483
 484    fn on_scroll_wheel(
 485        mut self,
 486        listener: impl Fn(&ScrollWheelEvent, &mut WindowContext) + 'static,
 487    ) -> Self {
 488        self.interactivity().on_scroll_wheel(listener);
 489        self
 490    }
 491
 492    /// Capture the given action, before normal action dispatch can fire
 493    fn capture_action<A: Action>(
 494        mut self,
 495        listener: impl Fn(&A, &mut WindowContext) + 'static,
 496    ) -> Self {
 497        self.interactivity().capture_action(listener);
 498        self
 499    }
 500
 501    /// Add a listener for the given action, fires during the bubble event phase
 502    fn on_action<A: Action>(mut self, listener: impl Fn(&A, &mut WindowContext) + 'static) -> Self {
 503        self.interactivity().on_action(listener);
 504        self
 505    }
 506
 507    fn on_boxed_action(
 508        mut self,
 509        action: &Box<dyn Action>,
 510        listener: impl Fn(&Box<dyn Action>, &mut WindowContext) + 'static,
 511    ) -> Self {
 512        self.interactivity().on_boxed_action(action, listener);
 513        self
 514    }
 515
 516    fn on_key_down(
 517        mut self,
 518        listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static,
 519    ) -> Self {
 520        self.interactivity().on_key_down(listener);
 521        self
 522    }
 523
 524    fn capture_key_down(
 525        mut self,
 526        listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static,
 527    ) -> Self {
 528        self.interactivity().capture_key_down(listener);
 529        self
 530    }
 531
 532    fn on_key_up(mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) -> Self {
 533        self.interactivity().on_key_up(listener);
 534        self
 535    }
 536
 537    fn capture_key_up(
 538        mut self,
 539        listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static,
 540    ) -> Self {
 541        self.interactivity().capture_key_up(listener);
 542        self
 543    }
 544
 545    fn drag_over<S: 'static>(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
 546        self.interactivity()
 547            .drag_over_styles
 548            .push((TypeId::of::<S>(), f(StyleRefinement::default())));
 549        self
 550    }
 551
 552    fn group_drag_over<S: 'static>(
 553        mut self,
 554        group_name: impl Into<SharedString>,
 555        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
 556    ) -> Self {
 557        self.interactivity().group_drag_over_styles.push((
 558            TypeId::of::<S>(),
 559            GroupStyle {
 560                group: group_name.into(),
 561                style: Box::new(f(StyleRefinement::default())),
 562            },
 563        ));
 564        self
 565    }
 566
 567    fn on_drop<T: 'static>(mut self, listener: impl Fn(&T, &mut WindowContext) + 'static) -> Self {
 568        self.interactivity().on_drop(listener);
 569        self
 570    }
 571
 572    fn block_mouse(mut self) -> Self {
 573        self.interactivity().block_mouse();
 574        self
 575    }
 576}
 577
 578pub trait StatefulInteractiveElement: InteractiveElement {
 579    fn focusable(mut self) -> Focusable<Self> {
 580        self.interactivity().focusable = true;
 581        Focusable { element: self }
 582    }
 583
 584    fn overflow_scroll(mut self) -> Self {
 585        self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
 586        self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
 587        self
 588    }
 589
 590    fn overflow_x_scroll(mut self) -> Self {
 591        self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
 592        self
 593    }
 594
 595    fn overflow_y_scroll(mut self) -> Self {
 596        self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
 597        self
 598    }
 599
 600    fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
 601        self.interactivity().scroll_handle = Some(scroll_handle.clone());
 602        self
 603    }
 604
 605    fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
 606    where
 607        Self: Sized,
 608    {
 609        self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
 610        self
 611    }
 612
 613    fn group_active(
 614        mut self,
 615        group_name: impl Into<SharedString>,
 616        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
 617    ) -> Self
 618    where
 619        Self: Sized,
 620    {
 621        self.interactivity().group_active_style = Some(GroupStyle {
 622            group: group_name.into(),
 623            style: Box::new(f(StyleRefinement::default())),
 624        });
 625        self
 626    }
 627
 628    fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut WindowContext) + 'static) -> Self
 629    where
 630        Self: Sized,
 631    {
 632        self.interactivity().on_click(listener);
 633        self
 634    }
 635
 636    fn on_drag<T, W>(
 637        mut self,
 638        value: T,
 639        constructor: impl Fn(&T, &mut WindowContext) -> View<W> + 'static,
 640    ) -> Self
 641    where
 642        Self: Sized,
 643        T: 'static,
 644        W: 'static + Render,
 645    {
 646        self.interactivity().on_drag(value, constructor);
 647        self
 648    }
 649
 650    fn on_hover(mut self, listener: impl Fn(&bool, &mut WindowContext) + 'static) -> Self
 651    where
 652        Self: Sized,
 653    {
 654        self.interactivity().on_hover(listener);
 655        self
 656    }
 657
 658    fn tooltip(mut self, build_tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) -> Self
 659    where
 660        Self: Sized,
 661    {
 662        self.interactivity().tooltip(build_tooltip);
 663        self
 664    }
 665}
 666
 667pub trait FocusableElement: InteractiveElement {
 668    fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
 669    where
 670        Self: Sized,
 671    {
 672        self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
 673        self
 674    }
 675
 676    fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
 677    where
 678        Self: Sized,
 679    {
 680        self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
 681        self
 682    }
 683}
 684
 685pub type MouseDownListener =
 686    Box<dyn Fn(&MouseDownEvent, &InteractiveBounds, DispatchPhase, &mut WindowContext) + 'static>;
 687pub type MouseUpListener =
 688    Box<dyn Fn(&MouseUpEvent, &InteractiveBounds, DispatchPhase, &mut WindowContext) + 'static>;
 689
 690pub type MouseMoveListener =
 691    Box<dyn Fn(&MouseMoveEvent, &InteractiveBounds, DispatchPhase, &mut WindowContext) + 'static>;
 692
 693pub type ScrollWheelListener =
 694    Box<dyn Fn(&ScrollWheelEvent, &InteractiveBounds, DispatchPhase, &mut WindowContext) + 'static>;
 695
 696pub type ClickListener = Box<dyn Fn(&ClickEvent, &mut WindowContext) + 'static>;
 697
 698pub type DragListener = Box<dyn Fn(&dyn Any, &mut WindowContext) -> AnyView + 'static>;
 699
 700type DropListener = Box<dyn Fn(&dyn Any, &mut WindowContext) + 'static>;
 701
 702pub type TooltipBuilder = Rc<dyn Fn(&mut WindowContext) -> AnyView + 'static>;
 703
 704pub type KeyDownListener = Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut WindowContext) + 'static>;
 705
 706pub type KeyUpListener = Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut WindowContext) + 'static>;
 707
 708pub type DragEventListener = Box<dyn Fn(&MouseMoveEvent, &mut WindowContext) + 'static>;
 709
 710pub type ActionListener = Box<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
 711
 712#[track_caller]
 713pub fn div() -> Div {
 714    #[cfg(debug_assertions)]
 715    let interactivity = {
 716        let mut interactivity = Interactivity::default();
 717        interactivity.location = Some(*core::panic::Location::caller());
 718        interactivity
 719    };
 720
 721    #[cfg(not(debug_assertions))]
 722    let interactivity = Interactivity::default();
 723
 724    Div {
 725        interactivity,
 726        children: SmallVec::default(),
 727    }
 728}
 729
 730pub struct Div {
 731    interactivity: Interactivity,
 732    children: SmallVec<[AnyElement; 2]>,
 733}
 734
 735impl Styled for Div {
 736    fn style(&mut self) -> &mut StyleRefinement {
 737        &mut self.interactivity.base_style
 738    }
 739}
 740
 741impl InteractiveElement for Div {
 742    fn interactivity(&mut self) -> &mut Interactivity {
 743        &mut self.interactivity
 744    }
 745}
 746
 747impl ParentElement for Div {
 748    fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> {
 749        &mut self.children
 750    }
 751}
 752
 753impl Element for Div {
 754    type State = DivState;
 755
 756    fn layout(
 757        &mut self,
 758        element_state: Option<Self::State>,
 759        cx: &mut WindowContext,
 760    ) -> (LayoutId, Self::State) {
 761        let mut child_layout_ids = SmallVec::new();
 762        let (layout_id, interactive_state) = self.interactivity.layout(
 763            element_state.map(|s| s.interactive_state),
 764            cx,
 765            |style, cx| {
 766                cx.with_text_style(style.text_style().cloned(), |cx| {
 767                    child_layout_ids = self
 768                        .children
 769                        .iter_mut()
 770                        .map(|child| child.layout(cx))
 771                        .collect::<SmallVec<_>>();
 772                    cx.request_layout(&style, child_layout_ids.iter().copied())
 773                })
 774            },
 775        );
 776        (
 777            layout_id,
 778            DivState {
 779                interactive_state,
 780                child_layout_ids,
 781            },
 782        )
 783    }
 784
 785    fn paint(
 786        &mut self,
 787        bounds: Bounds<Pixels>,
 788        element_state: &mut Self::State,
 789        cx: &mut WindowContext,
 790    ) {
 791        let mut child_min = point(Pixels::MAX, Pixels::MAX);
 792        let mut child_max = Point::default();
 793        let content_size = if element_state.child_layout_ids.is_empty() {
 794            bounds.size
 795        } else if let Some(scroll_handle) = self.interactivity.scroll_handle.as_ref() {
 796            let mut state = scroll_handle.0.borrow_mut();
 797            state.child_bounds = Vec::with_capacity(element_state.child_layout_ids.len());
 798            state.bounds = bounds;
 799            let requested = state.requested_scroll_top.take();
 800
 801            for (ix, child_layout_id) in element_state.child_layout_ids.iter().enumerate() {
 802                let child_bounds = cx.layout_bounds(*child_layout_id);
 803                child_min = child_min.min(&child_bounds.origin);
 804                child_max = child_max.max(&child_bounds.lower_right());
 805                state.child_bounds.push(child_bounds);
 806
 807                if let Some(requested) = requested.as_ref() {
 808                    if requested.0 == ix {
 809                        *state.offset.borrow_mut() =
 810                            bounds.origin - (child_bounds.origin - point(px(0.), requested.1));
 811                    }
 812                }
 813            }
 814            (child_max - child_min).into()
 815        } else {
 816            for child_layout_id in &element_state.child_layout_ids {
 817                let child_bounds = cx.layout_bounds(*child_layout_id);
 818                child_min = child_min.min(&child_bounds.origin);
 819                child_max = child_max.max(&child_bounds.lower_right());
 820            }
 821            (child_max - child_min).into()
 822        };
 823
 824        self.interactivity.paint(
 825            bounds,
 826            content_size,
 827            &mut element_state.interactive_state,
 828            cx,
 829            |_style, scroll_offset, cx| {
 830                cx.with_element_offset(scroll_offset, |cx| {
 831                    for child in &mut self.children {
 832                        child.paint(cx);
 833                    }
 834                })
 835            },
 836        );
 837    }
 838}
 839
 840impl IntoElement for Div {
 841    type Element = Self;
 842
 843    fn element_id(&self) -> Option<ElementId> {
 844        self.interactivity.element_id.clone()
 845    }
 846
 847    fn into_element(self) -> Self::Element {
 848        self
 849    }
 850}
 851
 852pub struct DivState {
 853    child_layout_ids: SmallVec<[LayoutId; 2]>,
 854    interactive_state: InteractiveElementState,
 855}
 856
 857impl DivState {
 858    pub fn is_active(&self) -> bool {
 859        self.interactive_state
 860            .pending_mouse_down
 861            .as_ref()
 862            .map_or(false, |pending| pending.borrow().is_some())
 863    }
 864}
 865
 866pub struct Interactivity {
 867    pub element_id: Option<ElementId>,
 868    pub key_context: Option<KeyContext>,
 869    pub focusable: bool,
 870    pub tracked_focus_handle: Option<FocusHandle>,
 871    pub scroll_handle: Option<ScrollHandle>,
 872    pub group: Option<SharedString>,
 873    pub base_style: Box<StyleRefinement>,
 874    pub focus_style: Option<Box<StyleRefinement>>,
 875    pub in_focus_style: Option<Box<StyleRefinement>>,
 876    pub hover_style: Option<Box<StyleRefinement>>,
 877    pub group_hover_style: Option<GroupStyle>,
 878    pub active_style: Option<Box<StyleRefinement>>,
 879    pub group_active_style: Option<GroupStyle>,
 880    pub drag_over_styles: Vec<(TypeId, StyleRefinement)>,
 881    pub group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
 882    pub mouse_down_listeners: Vec<MouseDownListener>,
 883    pub mouse_up_listeners: Vec<MouseUpListener>,
 884    pub mouse_move_listeners: Vec<MouseMoveListener>,
 885    pub scroll_wheel_listeners: Vec<ScrollWheelListener>,
 886    pub key_down_listeners: Vec<KeyDownListener>,
 887    pub key_up_listeners: Vec<KeyUpListener>,
 888    pub action_listeners: Vec<(TypeId, ActionListener)>,
 889    pub drop_listeners: Vec<(TypeId, DropListener)>,
 890    pub click_listeners: Vec<ClickListener>,
 891    pub drag_listener: Option<(Box<dyn Any>, DragListener)>,
 892    pub hover_listener: Option<Box<dyn Fn(&bool, &mut WindowContext)>>,
 893    pub tooltip_builder: Option<TooltipBuilder>,
 894    pub block_mouse: bool,
 895
 896    #[cfg(debug_assertions)]
 897    pub location: Option<core::panic::Location<'static>>,
 898}
 899
 900#[derive(Clone, Debug)]
 901pub struct InteractiveBounds {
 902    pub bounds: Bounds<Pixels>,
 903    pub stacking_order: StackingOrder,
 904}
 905
 906impl InteractiveBounds {
 907    pub fn visibly_contains(&self, point: &Point<Pixels>, cx: &WindowContext) -> bool {
 908        self.bounds.contains(point) && cx.was_top_layer(&point, &self.stacking_order)
 909    }
 910
 911    pub fn drag_target_contains(&self, point: &Point<Pixels>, cx: &WindowContext) -> bool {
 912        self.bounds.contains(point)
 913            && cx.was_top_layer_under_active_drag(&point, &self.stacking_order)
 914    }
 915}
 916
 917impl Interactivity {
 918    pub fn layout(
 919        &mut self,
 920        element_state: Option<InteractiveElementState>,
 921        cx: &mut WindowContext,
 922        f: impl FnOnce(Style, &mut WindowContext) -> LayoutId,
 923    ) -> (LayoutId, InteractiveElementState) {
 924        let mut element_state = element_state.unwrap_or_default();
 925
 926        if cx.has_active_drag() {
 927            if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
 928                *pending_mouse_down.borrow_mut() = None;
 929            }
 930            if let Some(clicked_state) = element_state.clicked_state.as_ref() {
 931                *clicked_state.borrow_mut() = ElementClickedState::default();
 932            }
 933        }
 934
 935        // Ensure we store a focus handle in our element state if we're focusable.
 936        // If there's an explicit focus handle we're tracking, use that. Otherwise
 937        // create a new handle and store it in the element state, which lives for as
 938        // as frames contain an element with this id.
 939        if self.focusable {
 940            element_state.focus_handle.get_or_insert_with(|| {
 941                self.tracked_focus_handle
 942                    .clone()
 943                    .unwrap_or_else(|| cx.focus_handle())
 944            });
 945        }
 946
 947        if let Some(scroll_handle) = self.scroll_handle.as_ref() {
 948            element_state.scroll_offset = Some(scroll_handle.0.borrow().offset.clone());
 949        }
 950
 951        let style = self.compute_style(None, &mut element_state, cx);
 952        let layout_id = f(style, cx);
 953        (layout_id, element_state)
 954    }
 955
 956    pub fn paint(
 957        &mut self,
 958        bounds: Bounds<Pixels>,
 959        content_size: Size<Pixels>,
 960        element_state: &mut InteractiveElementState,
 961        cx: &mut WindowContext,
 962        f: impl FnOnce(&Style, Point<Pixels>, &mut WindowContext),
 963    ) {
 964        let style = self.compute_style(Some(bounds), element_state, cx);
 965
 966        if style.visibility == Visibility::Hidden {
 967            return;
 968        }
 969
 970        let z_index = style.z_index.unwrap_or(0);
 971        cx.with_z_index(z_index, |cx| {
 972            style.paint(bounds, cx, |cx| {
 973                cx.with_text_style(style.text_style().cloned(), |cx| {
 974                    cx.with_content_mask(style.overflow_mask(bounds, cx.rem_size()), |cx| {
 975                        #[cfg(debug_assertions)]
 976                        if self.element_id.is_some()
 977                            && (style.debug
 978                                || style.debug_below
 979                                || cx.has_global::<crate::DebugBelow>())
 980                            && bounds.contains(&cx.mouse_position())
 981                        {
 982                            const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
 983                            let element_id = format!("{:?}", self.element_id.as_ref().unwrap());
 984                            let str_len = element_id.len();
 985
 986                            let render_debug_text = |cx: &mut WindowContext| {
 987                                if let Some(text) = cx
 988                                    .text_system()
 989                                    .shape_text(
 990                                        &element_id,
 991                                        FONT_SIZE,
 992                                        &[cx.text_style().to_run(str_len)],
 993                                        None,
 994                                    )
 995                                    .ok()
 996                                    .map(|mut text| text.pop())
 997                                    .flatten()
 998                                {
 999                                    text.paint(bounds.origin, FONT_SIZE, cx).ok();
1000
1001                                    let text_bounds = crate::Bounds {
1002                                        origin: bounds.origin,
1003                                        size: text.size(FONT_SIZE),
1004                                    };
1005                                    if self.location.is_some()
1006                                        && text_bounds.contains(&cx.mouse_position())
1007                                        && cx.modifiers().command
1008                                    {
1009                                        let command_held = cx.modifiers().command;
1010                                        cx.on_key_event({
1011                                            let text_bounds = text_bounds.clone();
1012                                            move |e: &crate::ModifiersChangedEvent, _phase, cx| {
1013                                                if e.modifiers.command != command_held
1014                                                    && text_bounds.contains(&cx.mouse_position())
1015                                                {
1016                                                    cx.notify();
1017                                                }
1018                                            }
1019                                        });
1020
1021                                        let hovered = bounds.contains(&cx.mouse_position());
1022                                        cx.on_mouse_event(
1023                                            move |event: &MouseMoveEvent, phase, cx| {
1024                                                if phase == DispatchPhase::Capture {
1025                                                    if bounds.contains(&event.position) != hovered {
1026                                                        cx.notify();
1027                                                    }
1028                                                }
1029                                            },
1030                                        );
1031
1032                                        cx.on_mouse_event({
1033                                            let location = self.location.clone().unwrap();
1034                                            let text_bounds = text_bounds.clone();
1035                                            move |e: &crate::MouseDownEvent, phase, cx| {
1036                                                if text_bounds.contains(&e.position)
1037                                                    && phase.capture()
1038                                                {
1039                                                    cx.stop_propagation();
1040                                                    let Ok(dir) = std::env::current_dir() else {
1041                                                        return;
1042                                                    };
1043
1044                                                    eprintln!(
1045                                                        "This element is created at:\n{}:{}:{}",
1046                                                        location.file(),
1047                                                        location.line(),
1048                                                        location.column()
1049                                                    );
1050
1051                                                    std::process::Command::new("zed")
1052                                                        .arg(format!(
1053                                                            "{}/{}:{}:{}",
1054                                                            dir.to_string_lossy(),
1055                                                            location.file(),
1056                                                            location.line(),
1057                                                            location.column()
1058                                                        ))
1059                                                        .spawn()
1060                                                        .ok();
1061                                                }
1062                                            }
1063                                        });
1064                                        cx.paint_quad(crate::outline(
1065                                            crate::Bounds {
1066                                                origin: bounds.origin
1067                                                    + crate::point(
1068                                                        crate::px(0.),
1069                                                        FONT_SIZE - px(2.),
1070                                                    ),
1071                                                size: crate::Size {
1072                                                    width: text_bounds.size.width,
1073                                                    height: crate::px(1.),
1074                                                },
1075                                            },
1076                                            crate::red(),
1077                                        ))
1078                                    }
1079                                }
1080                            };
1081
1082                            cx.with_z_index(1, |cx| {
1083                                cx.with_text_style(
1084                                    Some(crate::TextStyleRefinement {
1085                                        color: Some(crate::red()),
1086                                        line_height: Some(FONT_SIZE.into()),
1087                                        background_color: Some(crate::white()),
1088                                        ..Default::default()
1089                                    }),
1090                                    render_debug_text,
1091                                )
1092                            });
1093                        }
1094
1095                        let interactive_bounds = InteractiveBounds {
1096                            bounds: bounds.intersect(&cx.content_mask().bounds),
1097                            stacking_order: cx.stacking_order().clone(),
1098                        };
1099
1100                        if self.block_mouse
1101                            || style.background.as_ref().is_some_and(|fill| {
1102                                fill.color().is_some_and(|color| !color.is_transparent())
1103                            })
1104                        {
1105                            cx.add_opaque_layer(interactive_bounds.bounds);
1106                        }
1107
1108                        if !cx.has_active_drag() {
1109                            if let Some(mouse_cursor) = style.mouse_cursor {
1110                                let mouse_position = &cx.mouse_position();
1111                                let hovered =
1112                                    interactive_bounds.visibly_contains(mouse_position, cx);
1113                                if hovered {
1114                                    cx.set_cursor_style(mouse_cursor);
1115                                }
1116                            }
1117                        }
1118
1119                        // If this element can be focused, register a mouse down listener
1120                        // that will automatically transfer focus when hitting the element.
1121                        // This behavior can be suppressed by using `cx.prevent_default()`.
1122                        if let Some(focus_handle) = element_state.focus_handle.clone() {
1123                            cx.on_mouse_event({
1124                                let interactive_bounds = interactive_bounds.clone();
1125                                move |event: &MouseDownEvent, phase, cx| {
1126                                    if phase == DispatchPhase::Bubble
1127                                        && !cx.default_prevented()
1128                                        && interactive_bounds.visibly_contains(&event.position, cx)
1129                                    {
1130                                        cx.focus(&focus_handle);
1131                                        // If there is a parent that is also focusable, prevent it
1132                                        // from transferring focus because we already did so.
1133                                        cx.prevent_default();
1134                                    }
1135                                }
1136                            });
1137                        }
1138
1139                        for listener in self.mouse_down_listeners.drain(..) {
1140                            let interactive_bounds = interactive_bounds.clone();
1141                            cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| {
1142                                listener(event, &interactive_bounds, phase, cx);
1143                            })
1144                        }
1145
1146                        for listener in self.mouse_up_listeners.drain(..) {
1147                            let interactive_bounds = interactive_bounds.clone();
1148                            cx.on_mouse_event(move |event: &MouseUpEvent, phase, cx| {
1149                                listener(event, &interactive_bounds, phase, cx);
1150                            })
1151                        }
1152
1153                        for listener in self.mouse_move_listeners.drain(..) {
1154                            let interactive_bounds = interactive_bounds.clone();
1155                            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1156                                listener(event, &interactive_bounds, phase, cx);
1157                            })
1158                        }
1159
1160                        for listener in self.scroll_wheel_listeners.drain(..) {
1161                            let interactive_bounds = interactive_bounds.clone();
1162                            cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
1163                                listener(event, &interactive_bounds, phase, cx);
1164                            })
1165                        }
1166
1167                        let hover_group_bounds = self
1168                            .group_hover_style
1169                            .as_ref()
1170                            .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
1171
1172                        if let Some(group_bounds) = hover_group_bounds {
1173                            let hovered = group_bounds.contains(&cx.mouse_position());
1174                            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1175                                if phase == DispatchPhase::Capture {
1176                                    if group_bounds.contains(&event.position) != hovered {
1177                                        cx.notify();
1178                                    }
1179                                }
1180                            });
1181                        }
1182
1183                        if self.hover_style.is_some()
1184                            || self.base_style.mouse_cursor.is_some()
1185                            || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
1186                        {
1187                            let bounds = bounds.intersect(&cx.content_mask().bounds);
1188                            let hovered = bounds.contains(&cx.mouse_position());
1189                            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1190                                if phase == DispatchPhase::Capture {
1191                                    if bounds.contains(&event.position) != hovered {
1192                                        cx.notify();
1193                                    }
1194                                }
1195                            });
1196                        }
1197
1198                        let mut drag_listener = mem::take(&mut self.drag_listener);
1199                        let drop_listeners = mem::take(&mut self.drop_listeners);
1200                        let click_listeners = mem::take(&mut self.click_listeners);
1201
1202                        if !drop_listeners.is_empty() {
1203                            cx.on_mouse_event({
1204                                let interactive_bounds = interactive_bounds.clone();
1205                                move |event: &MouseUpEvent, phase, cx| {
1206                                    if let Some(drag) = &cx.active_drag {
1207                                        if phase == DispatchPhase::Bubble
1208                                            && interactive_bounds
1209                                                .drag_target_contains(&event.position, cx)
1210                                        {
1211                                            let drag_state_type = drag.value.as_ref().type_id();
1212                                            for (drop_state_type, listener) in &drop_listeners {
1213                                                if *drop_state_type == drag_state_type {
1214                                                    let drag = cx.active_drag.take().expect(
1215                                                        "checked for type drag state type above",
1216                                                    );
1217
1218                                                    listener(drag.value.as_ref(), cx);
1219                                                    cx.notify();
1220                                                    cx.stop_propagation();
1221                                                }
1222                                            }
1223                                        }
1224                                    }
1225                                }
1226                            });
1227                        }
1228
1229                        if !click_listeners.is_empty() || drag_listener.is_some() {
1230                            let pending_mouse_down = element_state
1231                                .pending_mouse_down
1232                                .get_or_insert_with(Default::default)
1233                                .clone();
1234
1235                            let clicked_state = element_state
1236                                .clicked_state
1237                                .get_or_insert_with(Default::default)
1238                                .clone();
1239
1240                            cx.on_mouse_event({
1241                                let interactive_bounds = interactive_bounds.clone();
1242                                let pending_mouse_down = pending_mouse_down.clone();
1243                                move |event: &MouseDownEvent, phase, cx| {
1244                                    if phase == DispatchPhase::Bubble
1245                                        && event.button == MouseButton::Left
1246                                        && interactive_bounds.visibly_contains(&event.position, cx)
1247                                    {
1248                                        *pending_mouse_down.borrow_mut() = Some(event.clone());
1249                                        cx.notify();
1250                                    }
1251                                }
1252                            });
1253
1254                            cx.on_mouse_event({
1255                                let pending_mouse_down = pending_mouse_down.clone();
1256                                move |event: &MouseMoveEvent, phase, cx| {
1257                                    if phase == DispatchPhase::Capture {
1258                                        return;
1259                                    }
1260
1261                                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
1262                                    if let Some(mouse_down) = pending_mouse_down.clone() {
1263                                        if !cx.has_active_drag()
1264                                            && (event.position - mouse_down.position).magnitude()
1265                                                > DRAG_THRESHOLD
1266                                        {
1267                                            if let Some((drag_value, drag_listener)) =
1268                                                drag_listener.take()
1269                                            {
1270                                                *clicked_state.borrow_mut() =
1271                                                    ElementClickedState::default();
1272                                                let cursor_offset = event.position - bounds.origin;
1273                                                let drag = (drag_listener)(drag_value.as_ref(), cx);
1274                                                cx.active_drag = Some(AnyDrag {
1275                                                    view: drag,
1276                                                    value: drag_value,
1277                                                    cursor_offset,
1278                                                });
1279                                                pending_mouse_down.take();
1280                                                cx.notify();
1281                                                cx.stop_propagation();
1282                                            }
1283                                        }
1284                                    }
1285                                }
1286                            });
1287
1288                            cx.on_mouse_event({
1289                                let interactive_bounds = interactive_bounds.clone();
1290                                let mut captured_mouse_down = None;
1291                                move |event: &MouseUpEvent, phase, cx| match phase {
1292                                    // Clear the pending mouse down during the capture phase,
1293                                    // so that it happens even if another event handler stops
1294                                    // propagation.
1295                                    DispatchPhase::Capture => {
1296                                        let mut pending_mouse_down =
1297                                            pending_mouse_down.borrow_mut();
1298                                        if pending_mouse_down.is_some() {
1299                                            captured_mouse_down = pending_mouse_down.take();
1300                                            cx.notify();
1301                                        }
1302                                    }
1303                                    // Fire click handlers during the bubble phase.
1304                                    DispatchPhase::Bubble => {
1305                                        if let Some(mouse_down) = captured_mouse_down.take() {
1306                                            if interactive_bounds
1307                                                .visibly_contains(&event.position, cx)
1308                                            {
1309                                                let mouse_click = ClickEvent {
1310                                                    down: mouse_down,
1311                                                    up: event.clone(),
1312                                                };
1313                                                for listener in &click_listeners {
1314                                                    listener(&mouse_click, cx);
1315                                                }
1316                                            }
1317                                        }
1318                                    }
1319                                }
1320                            });
1321                        }
1322
1323                        if let Some(hover_listener) = self.hover_listener.take() {
1324                            let was_hovered = element_state
1325                                .hover_state
1326                                .get_or_insert_with(Default::default)
1327                                .clone();
1328                            let has_mouse_down = element_state
1329                                .pending_mouse_down
1330                                .get_or_insert_with(Default::default)
1331                                .clone();
1332                            let interactive_bounds = interactive_bounds.clone();
1333
1334                            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1335                                if phase != DispatchPhase::Bubble {
1336                                    return;
1337                                }
1338                                let is_hovered = interactive_bounds
1339                                    .visibly_contains(&event.position, cx)
1340                                    && has_mouse_down.borrow().is_none()
1341                                    && !cx.has_active_drag();
1342                                let mut was_hovered = was_hovered.borrow_mut();
1343
1344                                if is_hovered != was_hovered.clone() {
1345                                    *was_hovered = is_hovered;
1346                                    drop(was_hovered);
1347
1348                                    hover_listener(&is_hovered, cx);
1349                                }
1350                            });
1351                        }
1352
1353                        if let Some(tooltip_builder) = self.tooltip_builder.take() {
1354                            let active_tooltip = element_state
1355                                .active_tooltip
1356                                .get_or_insert_with(Default::default)
1357                                .clone();
1358                            let pending_mouse_down = element_state
1359                                .pending_mouse_down
1360                                .get_or_insert_with(Default::default)
1361                                .clone();
1362                            let interactive_bounds = interactive_bounds.clone();
1363
1364                            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1365                                let is_hovered = interactive_bounds
1366                                    .visibly_contains(&event.position, cx)
1367                                    && pending_mouse_down.borrow().is_none();
1368                                if !is_hovered {
1369                                    active_tooltip.borrow_mut().take();
1370                                    return;
1371                                }
1372
1373                                if phase != DispatchPhase::Bubble {
1374                                    return;
1375                                }
1376
1377                                if active_tooltip.borrow().is_none() {
1378                                    let task = cx.spawn({
1379                                        let active_tooltip = active_tooltip.clone();
1380                                        let tooltip_builder = tooltip_builder.clone();
1381
1382                                        move |mut cx| async move {
1383                                            cx.background_executor().timer(TOOLTIP_DELAY).await;
1384                                            cx.update(|_, cx| {
1385                                                active_tooltip.borrow_mut().replace(
1386                                                    ActiveTooltip {
1387                                                        tooltip: Some(AnyTooltip {
1388                                                            view: tooltip_builder(cx),
1389                                                            cursor_offset: cx.mouse_position(),
1390                                                        }),
1391                                                        _task: None,
1392                                                    },
1393                                                );
1394                                                cx.notify();
1395                                            })
1396                                            .ok();
1397                                        }
1398                                    });
1399                                    active_tooltip.borrow_mut().replace(ActiveTooltip {
1400                                        tooltip: None,
1401                                        _task: Some(task),
1402                                    });
1403                                }
1404                            });
1405
1406                            let active_tooltip = element_state
1407                                .active_tooltip
1408                                .get_or_insert_with(Default::default)
1409                                .clone();
1410                            cx.on_mouse_event(move |_: &MouseDownEvent, _, _| {
1411                                active_tooltip.borrow_mut().take();
1412                            });
1413
1414                            if let Some(active_tooltip) = element_state
1415                                .active_tooltip
1416                                .get_or_insert_with(Default::default)
1417                                .borrow()
1418                                .as_ref()
1419                            {
1420                                if active_tooltip.tooltip.is_some() {
1421                                    cx.active_tooltip = active_tooltip.tooltip.clone()
1422                                }
1423                            }
1424                        }
1425
1426                        let active_state = element_state
1427                            .clicked_state
1428                            .get_or_insert_with(Default::default)
1429                            .clone();
1430                        if active_state.borrow().is_clicked() {
1431                            cx.on_mouse_event(move |_: &MouseUpEvent, phase, cx| {
1432                                if phase == DispatchPhase::Capture {
1433                                    *active_state.borrow_mut() = ElementClickedState::default();
1434                                    cx.notify();
1435                                }
1436                            });
1437                        } else {
1438                            let active_group_bounds = self
1439                                .group_active_style
1440                                .as_ref()
1441                                .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
1442                            let interactive_bounds = interactive_bounds.clone();
1443                            cx.on_mouse_event(move |down: &MouseDownEvent, phase, cx| {
1444                                if phase == DispatchPhase::Bubble && !cx.default_prevented() {
1445                                    let group = active_group_bounds
1446                                        .map_or(false, |bounds| bounds.contains(&down.position));
1447                                    let element =
1448                                        interactive_bounds.visibly_contains(&down.position, cx);
1449                                    if group || element {
1450                                        *active_state.borrow_mut() =
1451                                            ElementClickedState { group, element };
1452                                        cx.notify();
1453                                    }
1454                                }
1455                            });
1456                        }
1457
1458                        let overflow = style.overflow;
1459                        if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
1460                            if let Some(scroll_handle) = &self.scroll_handle {
1461                                scroll_handle.0.borrow_mut().overflow = overflow;
1462                            }
1463
1464                            let scroll_offset = element_state
1465                                .scroll_offset
1466                                .get_or_insert_with(Rc::default)
1467                                .clone();
1468                            let line_height = cx.line_height();
1469                            let scroll_max = (content_size - bounds.size).max(&Size::default());
1470                            // Clamp scroll offset in case scroll max is smaller now (e.g., if children
1471                            // were removed or the bounds became larger).
1472                            {
1473                                let mut scroll_offset = scroll_offset.borrow_mut();
1474                                scroll_offset.x = scroll_offset.x.clamp(-scroll_max.width, px(0.));
1475                                scroll_offset.y = scroll_offset.y.clamp(-scroll_max.height, px(0.));
1476                            }
1477
1478                            let interactive_bounds = interactive_bounds.clone();
1479                            cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
1480                                if phase == DispatchPhase::Bubble
1481                                    && interactive_bounds.visibly_contains(&event.position, cx)
1482                                {
1483                                    let mut scroll_offset = scroll_offset.borrow_mut();
1484                                    let old_scroll_offset = *scroll_offset;
1485                                    let delta = event.delta.pixel_delta(line_height);
1486
1487                                    if overflow.x == Overflow::Scroll {
1488                                        scroll_offset.x = (scroll_offset.x + delta.x)
1489                                            .clamp(-scroll_max.width, px(0.));
1490                                    }
1491
1492                                    if overflow.y == Overflow::Scroll {
1493                                        scroll_offset.y = (scroll_offset.y + delta.y)
1494                                            .clamp(-scroll_max.height, px(0.));
1495                                    }
1496
1497                                    if *scroll_offset != old_scroll_offset {
1498                                        cx.notify();
1499                                        cx.stop_propagation();
1500                                    }
1501                                }
1502                            });
1503                        }
1504
1505                        if let Some(group) = self.group.clone() {
1506                            GroupBounds::push(group, bounds, cx);
1507                        }
1508
1509                        let scroll_offset = element_state
1510                            .scroll_offset
1511                            .as_ref()
1512                            .map(|scroll_offset| *scroll_offset.borrow());
1513
1514                        let key_down_listeners = mem::take(&mut self.key_down_listeners);
1515                        let key_up_listeners = mem::take(&mut self.key_up_listeners);
1516                        let action_listeners = mem::take(&mut self.action_listeners);
1517                        cx.with_key_dispatch(
1518                            self.key_context.clone(),
1519                            element_state.focus_handle.clone(),
1520                            |_, cx| {
1521                                for listener in key_down_listeners {
1522                                    cx.on_key_event(move |event: &KeyDownEvent, phase, cx| {
1523                                        listener(event, phase, cx);
1524                                    })
1525                                }
1526
1527                                for listener in key_up_listeners {
1528                                    cx.on_key_event(move |event: &KeyUpEvent, phase, cx| {
1529                                        listener(event, phase, cx);
1530                                    })
1531                                }
1532
1533                                for (action_type, listener) in action_listeners {
1534                                    cx.on_action(action_type, listener)
1535                                }
1536
1537                                f(&style, scroll_offset.unwrap_or_default(), cx)
1538                            },
1539                        );
1540
1541                        if let Some(group) = self.group.as_ref() {
1542                            GroupBounds::pop(group, cx);
1543                        }
1544                    });
1545                });
1546            });
1547        });
1548    }
1549
1550    pub fn compute_style(
1551        &self,
1552        bounds: Option<Bounds<Pixels>>,
1553        element_state: &mut InteractiveElementState,
1554        cx: &mut WindowContext,
1555    ) -> Style {
1556        let mut style = Style::default();
1557        style.refine(&self.base_style);
1558
1559        cx.with_z_index(style.z_index.unwrap_or(0), |cx| {
1560            if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
1561                if let Some(in_focus_style) = self.in_focus_style.as_ref() {
1562                    if focus_handle.within_focused(cx) {
1563                        style.refine(in_focus_style);
1564                    }
1565                }
1566
1567                if let Some(focus_style) = self.focus_style.as_ref() {
1568                    if focus_handle.is_focused(cx) {
1569                        style.refine(focus_style);
1570                    }
1571                }
1572            }
1573
1574            if let Some(bounds) = bounds {
1575                let mouse_position = cx.mouse_position();
1576                if !cx.has_active_drag() {
1577                    if let Some(group_hover) = self.group_hover_style.as_ref() {
1578                        if let Some(group_bounds) = GroupBounds::get(&group_hover.group, cx) {
1579                            if group_bounds.contains(&mouse_position)
1580                                && cx.was_top_layer(&mouse_position, cx.stacking_order())
1581                            {
1582                                style.refine(&group_hover.style);
1583                            }
1584                        }
1585                    }
1586
1587                    if let Some(hover_style) = self.hover_style.as_ref() {
1588                        if bounds
1589                            .intersect(&cx.content_mask().bounds)
1590                            .contains(&mouse_position)
1591                            && cx.was_top_layer(&mouse_position, cx.stacking_order())
1592                        {
1593                            style.refine(hover_style);
1594                        }
1595                    }
1596                }
1597
1598                if let Some(drag) = cx.active_drag.take() {
1599                    for (state_type, group_drag_style) in &self.group_drag_over_styles {
1600                        if let Some(group_bounds) = GroupBounds::get(&group_drag_style.group, cx) {
1601                            if *state_type == drag.value.as_ref().type_id()
1602                                && group_bounds.contains(&mouse_position)
1603                            {
1604                                style.refine(&group_drag_style.style);
1605                            }
1606                        }
1607                    }
1608
1609                    for (state_type, drag_over_style) in &self.drag_over_styles {
1610                        if *state_type == drag.value.as_ref().type_id()
1611                            && bounds
1612                                .intersect(&cx.content_mask().bounds)
1613                                .contains(&mouse_position)
1614                            && cx.was_top_layer_under_active_drag(
1615                                &mouse_position,
1616                                cx.stacking_order(),
1617                            )
1618                        {
1619                            style.refine(drag_over_style);
1620                        }
1621                    }
1622
1623                    cx.active_drag = Some(drag);
1624                }
1625            }
1626
1627            let clicked_state = element_state
1628                .clicked_state
1629                .get_or_insert_with(Default::default)
1630                .borrow();
1631            if clicked_state.group {
1632                if let Some(group) = self.group_active_style.as_ref() {
1633                    style.refine(&group.style)
1634                }
1635            }
1636
1637            if let Some(active_style) = self.active_style.as_ref() {
1638                if clicked_state.element {
1639                    style.refine(active_style)
1640                }
1641            }
1642        });
1643
1644        style
1645    }
1646}
1647
1648impl Default for Interactivity {
1649    fn default() -> Self {
1650        Self {
1651            element_id: None,
1652            key_context: None,
1653            focusable: false,
1654            tracked_focus_handle: None,
1655            scroll_handle: None,
1656            // scroll_offset: Point::default(),
1657            group: None,
1658            base_style: Box::new(StyleRefinement::default()),
1659            focus_style: None,
1660            in_focus_style: None,
1661            hover_style: None,
1662            group_hover_style: None,
1663            active_style: None,
1664            group_active_style: None,
1665            drag_over_styles: Vec::new(),
1666            group_drag_over_styles: Vec::new(),
1667            mouse_down_listeners: Vec::new(),
1668            mouse_up_listeners: Vec::new(),
1669            mouse_move_listeners: Vec::new(),
1670            scroll_wheel_listeners: Vec::new(),
1671            key_down_listeners: Vec::new(),
1672            key_up_listeners: Vec::new(),
1673            action_listeners: Vec::new(),
1674            drop_listeners: Vec::new(),
1675            click_listeners: Vec::new(),
1676            drag_listener: None,
1677            hover_listener: None,
1678            tooltip_builder: None,
1679            block_mouse: false,
1680
1681            #[cfg(debug_assertions)]
1682            location: None,
1683        }
1684    }
1685}
1686
1687#[derive(Default)]
1688pub struct InteractiveElementState {
1689    pub focus_handle: Option<FocusHandle>,
1690    pub clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
1691    pub hover_state: Option<Rc<RefCell<bool>>>,
1692    pub pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
1693    pub scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
1694    pub active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
1695}
1696
1697pub struct ActiveTooltip {
1698    tooltip: Option<AnyTooltip>,
1699    _task: Option<Task<()>>,
1700}
1701
1702/// Whether or not the element or a group that contains it is clicked by the mouse.
1703#[derive(Copy, Clone, Default, Eq, PartialEq)]
1704pub struct ElementClickedState {
1705    pub group: bool,
1706    pub element: bool,
1707}
1708
1709impl ElementClickedState {
1710    fn is_clicked(&self) -> bool {
1711        self.group || self.element
1712    }
1713}
1714
1715#[derive(Default)]
1716pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
1717
1718impl GroupBounds {
1719    pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
1720        cx.default_global::<Self>()
1721            .0
1722            .get(name)
1723            .and_then(|bounds_stack| bounds_stack.last())
1724            .cloned()
1725    }
1726
1727    pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
1728        cx.default_global::<Self>()
1729            .0
1730            .entry(name)
1731            .or_default()
1732            .push(bounds);
1733    }
1734
1735    pub fn pop(name: &SharedString, cx: &mut AppContext) {
1736        cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
1737    }
1738}
1739
1740pub struct Focusable<E> {
1741    pub element: E,
1742}
1743
1744impl<E: InteractiveElement> FocusableElement for Focusable<E> {}
1745
1746impl<E> InteractiveElement for Focusable<E>
1747where
1748    E: InteractiveElement,
1749{
1750    fn interactivity(&mut self) -> &mut Interactivity {
1751        self.element.interactivity()
1752    }
1753}
1754
1755impl<E: StatefulInteractiveElement> StatefulInteractiveElement for Focusable<E> {}
1756
1757impl<E> Styled for Focusable<E>
1758where
1759    E: Styled,
1760{
1761    fn style(&mut self) -> &mut StyleRefinement {
1762        self.element.style()
1763    }
1764}
1765
1766impl<E> Element for Focusable<E>
1767where
1768    E: Element,
1769{
1770    type State = E::State;
1771
1772    fn layout(
1773        &mut self,
1774        state: Option<Self::State>,
1775        cx: &mut WindowContext,
1776    ) -> (LayoutId, Self::State) {
1777        self.element.layout(state, cx)
1778    }
1779
1780    fn paint(&mut self, bounds: Bounds<Pixels>, state: &mut Self::State, cx: &mut WindowContext) {
1781        self.element.paint(bounds, state, cx)
1782    }
1783}
1784
1785impl<E> IntoElement for Focusable<E>
1786where
1787    E: IntoElement,
1788{
1789    type Element = E::Element;
1790
1791    fn element_id(&self) -> Option<ElementId> {
1792        self.element.element_id()
1793    }
1794
1795    fn into_element(self) -> Self::Element {
1796        self.element.into_element()
1797    }
1798}
1799
1800impl<E> ParentElement for Focusable<E>
1801where
1802    E: ParentElement,
1803{
1804    fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> {
1805        self.element.children_mut()
1806    }
1807}
1808
1809pub struct Stateful<E> {
1810    element: E,
1811}
1812
1813impl<E> Styled for Stateful<E>
1814where
1815    E: Styled,
1816{
1817    fn style(&mut self) -> &mut StyleRefinement {
1818        self.element.style()
1819    }
1820}
1821
1822impl<E> StatefulInteractiveElement for Stateful<E>
1823where
1824    E: Element,
1825    Self: InteractiveElement,
1826{
1827}
1828
1829impl<E> InteractiveElement for Stateful<E>
1830where
1831    E: InteractiveElement,
1832{
1833    fn interactivity(&mut self) -> &mut Interactivity {
1834        self.element.interactivity()
1835    }
1836}
1837
1838impl<E: FocusableElement> FocusableElement for Stateful<E> {}
1839
1840impl<E> Element for Stateful<E>
1841where
1842    E: Element,
1843{
1844    type State = E::State;
1845
1846    fn layout(
1847        &mut self,
1848        state: Option<Self::State>,
1849        cx: &mut WindowContext,
1850    ) -> (LayoutId, Self::State) {
1851        self.element.layout(state, cx)
1852    }
1853
1854    fn paint(&mut self, bounds: Bounds<Pixels>, state: &mut Self::State, cx: &mut WindowContext) {
1855        self.element.paint(bounds, state, cx)
1856    }
1857}
1858
1859impl<E> IntoElement for Stateful<E>
1860where
1861    E: Element,
1862{
1863    type Element = Self;
1864
1865    fn element_id(&self) -> Option<ElementId> {
1866        self.element.element_id()
1867    }
1868
1869    fn into_element(self) -> Self::Element {
1870        self
1871    }
1872}
1873
1874impl<E> ParentElement for Stateful<E>
1875where
1876    E: ParentElement,
1877{
1878    fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> {
1879        self.element.children_mut()
1880    }
1881}
1882
1883#[derive(Default)]
1884struct ScrollHandleState {
1885    // not great to have the nested rc's...
1886    offset: Rc<RefCell<Point<Pixels>>>,
1887    bounds: Bounds<Pixels>,
1888    child_bounds: Vec<Bounds<Pixels>>,
1889    requested_scroll_top: Option<(usize, Pixels)>,
1890    overflow: Point<Overflow>,
1891}
1892
1893#[derive(Clone)]
1894pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
1895
1896impl ScrollHandle {
1897    pub fn new() -> Self {
1898        Self(Rc::default())
1899    }
1900
1901    pub fn offset(&self) -> Point<Pixels> {
1902        self.0.borrow().offset.borrow().clone()
1903    }
1904
1905    pub fn top_item(&self) -> usize {
1906        let state = self.0.borrow();
1907        let top = state.bounds.top() - state.offset.borrow().y;
1908
1909        match state.child_bounds.binary_search_by(|bounds| {
1910            if top < bounds.top() {
1911                Ordering::Greater
1912            } else if top > bounds.bottom() {
1913                Ordering::Less
1914            } else {
1915                Ordering::Equal
1916            }
1917        }) {
1918            Ok(ix) => ix,
1919            Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
1920        }
1921    }
1922
1923    pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
1924        self.0.borrow().child_bounds.get(ix).cloned()
1925    }
1926
1927    /// scroll_to_item scrolls the minimal amount to ensure that the item is
1928    /// fully visible
1929    pub fn scroll_to_item(&self, ix: usize) {
1930        let state = self.0.borrow();
1931
1932        let Some(bounds) = state.child_bounds.get(ix) else {
1933            return;
1934        };
1935
1936        let mut scroll_offset = state.offset.borrow_mut();
1937
1938        if state.overflow.y == Overflow::Scroll {
1939            if bounds.top() + scroll_offset.y < state.bounds.top() {
1940                scroll_offset.y = state.bounds.top() - bounds.top();
1941            } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
1942                scroll_offset.y = state.bounds.bottom() - bounds.bottom();
1943            }
1944        }
1945
1946        if state.overflow.x == Overflow::Scroll {
1947            if bounds.left() + scroll_offset.x < state.bounds.left() {
1948                scroll_offset.x = state.bounds.left() - bounds.left();
1949            } else if bounds.right() + scroll_offset.x > state.bounds.right() {
1950                scroll_offset.x = state.bounds.right() - bounds.right();
1951            }
1952        }
1953    }
1954
1955    pub fn logical_scroll_top(&self) -> (usize, Pixels) {
1956        let ix = self.top_item();
1957        let state = self.0.borrow();
1958
1959        if let Some(child_bounds) = state.child_bounds.get(ix) {
1960            (
1961                ix,
1962                child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
1963            )
1964        } else {
1965            (ix, px(0.))
1966        }
1967    }
1968
1969    pub fn set_logical_scroll_top(&self, ix: usize, px: Pixels) {
1970        self.0.borrow_mut().requested_scroll_top = Some((ix, px));
1971    }
1972}