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