div.rs

   1use crate::{
   2    point, px, Action, AnyDrag, AnyElement, AnyTooltip, AnyView, AppContext, BorrowAppContext,
   3    BorrowWindow, Bounds, ClickEvent, DispatchPhase, Element, ElementId, FocusHandle, IntoElement,
   4    IsZero, KeyContext, KeyDownEvent, KeyUpEvent, LayoutId, MouseButton, MouseDownEvent,
   5    MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, Point, Render, ScrollWheelEvent,
   6    SharedString, Size, StackingOrder, Style, StyleRefinement, Styled, Task, View, Visibility,
   7    WindowContext,
   8};
   9
  10use collections::HashMap;
  11use refineable::Refineable;
  12use smallvec::SmallVec;
  13use std::{
  14    any::{Any, TypeId},
  15    cell::RefCell,
  16    cmp::Ordering,
  17    fmt::Debug,
  18    marker::PhantomData,
  19    mem,
  20    rc::Rc,
  21    time::Duration,
  22};
  23use taffy::style::Overflow;
  24use util::ResultExt;
  25
  26const DRAG_THRESHOLD: f64 = 2.;
  27const TOOLTIP_DELAY: Duration = Duration::from_millis(500);
  28
  29pub struct GroupStyle {
  30    pub group: SharedString,
  31    pub style: Box<StyleRefinement>,
  32}
  33
  34pub struct DragMoveEvent<T> {
  35    pub event: MouseMoveEvent,
  36    pub bounds: Bounds<Pixels>,
  37    drag: PhantomData<T>,
  38}
  39
  40impl<T: 'static> DragMoveEvent<T> {
  41    pub fn drag<'b>(&self, cx: &'b AppContext) -> &'b T {
  42        cx.active_drag
  43            .as_ref()
  44            .and_then(|drag| drag.value.downcast_ref::<T>())
  45            .expect("DragMoveEvent is only valid when the stored active drag is of the same type.")
  46    }
  47}
  48
  49impl Interactivity {
  50    pub fn on_mouse_down(
  51        &mut self,
  52        button: MouseButton,
  53        listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
  54    ) {
  55        self.mouse_down_listeners
  56            .push(Box::new(move |event, bounds, phase, cx| {
  57                if phase == DispatchPhase::Bubble
  58                    && event.button == button
  59                    && bounds.visibly_contains(&event.position, cx)
  60                {
  61                    (listener)(event, cx)
  62                }
  63            }));
  64    }
  65
  66    pub fn capture_any_mouse_down(
  67        &mut self,
  68        listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
  69    ) {
  70        self.mouse_down_listeners
  71            .push(Box::new(move |event, bounds, phase, cx| {
  72                if phase == DispatchPhase::Capture && bounds.visibly_contains(&event.position, cx) {
  73                    (listener)(event, cx)
  74                }
  75            }));
  76    }
  77
  78    pub fn on_any_mouse_down(
  79        &mut self,
  80        listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
  81    ) {
  82        self.mouse_down_listeners
  83            .push(Box::new(move |event, bounds, phase, cx| {
  84                if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) {
  85                    (listener)(event, cx)
  86                }
  87            }));
  88    }
  89
  90    pub fn on_mouse_up(
  91        &mut self,
  92        button: MouseButton,
  93        listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
  94    ) {
  95        self.mouse_up_listeners
  96            .push(Box::new(move |event, bounds, phase, cx| {
  97                if phase == DispatchPhase::Bubble
  98                    && event.button == button
  99                    && bounds.visibly_contains(&event.position, cx)
 100                {
 101                    (listener)(event, cx)
 102                }
 103            }));
 104    }
 105
 106    pub fn capture_any_mouse_up(
 107        &mut self,
 108        listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
 109    ) {
 110        self.mouse_up_listeners
 111            .push(Box::new(move |event, bounds, phase, cx| {
 112                if phase == DispatchPhase::Capture && bounds.visibly_contains(&event.position, cx) {
 113                    (listener)(event, cx)
 114                }
 115            }));
 116    }
 117
 118    pub fn on_any_mouse_up(
 119        &mut self,
 120        listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
 121    ) {
 122        self.mouse_up_listeners
 123            .push(Box::new(move |event, bounds, phase, cx| {
 124                if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) {
 125                    (listener)(event, cx)
 126                }
 127            }));
 128    }
 129
 130    pub fn on_mouse_down_out(
 131        &mut self,
 132        listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
 133    ) {
 134        self.mouse_down_listeners
 135            .push(Box::new(move |event, bounds, phase, cx| {
 136                if phase == DispatchPhase::Capture && !bounds.visibly_contains(&event.position, cx)
 137                {
 138                    (listener)(event, cx)
 139                }
 140            }));
 141    }
 142
 143    pub fn on_mouse_up_out(
 144        &mut self,
 145        button: MouseButton,
 146        listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
 147    ) {
 148        self.mouse_up_listeners
 149            .push(Box::new(move |event, bounds, phase, cx| {
 150                if phase == DispatchPhase::Capture
 151                    && event.button == button
 152                    && !bounds.visibly_contains(&event.position, cx)
 153                {
 154                    (listener)(event, cx);
 155                }
 156            }));
 157    }
 158
 159    pub fn on_mouse_move(
 160        &mut self,
 161        listener: impl Fn(&MouseMoveEvent, &mut WindowContext) + 'static,
 162    ) {
 163        self.mouse_move_listeners
 164            .push(Box::new(move |event, bounds, phase, cx| {
 165                if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) {
 166                    (listener)(event, cx);
 167                }
 168            }));
 169    }
 170
 171    pub fn on_drag_move<T>(
 172        &mut self,
 173        listener: impl Fn(&DragMoveEvent<T>, &mut WindowContext) + 'static,
 174    ) where
 175        T: 'static,
 176    {
 177        self.mouse_move_listeners
 178            .push(Box::new(move |event, bounds, phase, cx| {
 179                if phase == DispatchPhase::Capture
 180                    && cx
 181                        .active_drag
 182                        .as_ref()
 183                        .is_some_and(|drag| drag.value.as_ref().type_id() == TypeId::of::<T>())
 184                {
 185                    (listener)(
 186                        &DragMoveEvent {
 187                            event: event.clone(),
 188                            bounds: bounds.bounds,
 189                            drag: PhantomData,
 190                        },
 191                        cx,
 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: &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: &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 request_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.request_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
 880#[derive(Default)]
 881pub struct Interactivity {
 882    pub element_id: Option<ElementId>,
 883    pub key_context: Option<KeyContext>,
 884    pub focusable: bool,
 885    pub tracked_focus_handle: Option<FocusHandle>,
 886    pub scroll_handle: Option<ScrollHandle>,
 887    pub group: Option<SharedString>,
 888    pub base_style: Box<StyleRefinement>,
 889    pub focus_style: Option<Box<StyleRefinement>>,
 890    pub in_focus_style: Option<Box<StyleRefinement>>,
 891    pub hover_style: Option<Box<StyleRefinement>>,
 892    pub group_hover_style: Option<GroupStyle>,
 893    pub active_style: Option<Box<StyleRefinement>>,
 894    pub group_active_style: Option<GroupStyle>,
 895    pub drag_over_styles: Vec<(TypeId, StyleRefinement)>,
 896    pub group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
 897    pub mouse_down_listeners: Vec<MouseDownListener>,
 898    pub mouse_up_listeners: Vec<MouseUpListener>,
 899    pub mouse_move_listeners: Vec<MouseMoveListener>,
 900    pub scroll_wheel_listeners: Vec<ScrollWheelListener>,
 901    pub key_down_listeners: Vec<KeyDownListener>,
 902    pub key_up_listeners: Vec<KeyUpListener>,
 903    pub action_listeners: Vec<(TypeId, ActionListener)>,
 904    pub drop_listeners: Vec<(TypeId, DropListener)>,
 905    pub can_drop_predicate: Option<CanDropPredicate>,
 906    pub click_listeners: Vec<ClickListener>,
 907    pub drag_listener: Option<(Box<dyn Any>, DragListener)>,
 908    pub hover_listener: Option<Box<dyn Fn(&bool, &mut WindowContext)>>,
 909    pub tooltip_builder: Option<TooltipBuilder>,
 910    pub block_mouse: bool,
 911
 912    #[cfg(debug_assertions)]
 913    pub location: Option<core::panic::Location<'static>>,
 914}
 915
 916#[derive(Clone, Debug)]
 917pub struct InteractiveBounds {
 918    pub bounds: Bounds<Pixels>,
 919    pub stacking_order: StackingOrder,
 920}
 921
 922impl InteractiveBounds {
 923    pub fn visibly_contains(&self, point: &Point<Pixels>, cx: &WindowContext) -> bool {
 924        self.bounds.contains(point) && cx.was_top_layer(point, &self.stacking_order)
 925    }
 926
 927    pub fn drag_target_contains(&self, point: &Point<Pixels>, cx: &WindowContext) -> bool {
 928        self.bounds.contains(point)
 929            && cx.was_top_layer_under_active_drag(point, &self.stacking_order)
 930    }
 931}
 932
 933impl Interactivity {
 934    pub fn layout(
 935        &mut self,
 936        element_state: Option<InteractiveElementState>,
 937        cx: &mut WindowContext,
 938        f: impl FnOnce(Style, &mut WindowContext) -> LayoutId,
 939    ) -> (LayoutId, InteractiveElementState) {
 940        let mut element_state = element_state.unwrap_or_default();
 941
 942        if cx.has_active_drag() {
 943            if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
 944                *pending_mouse_down.borrow_mut() = None;
 945            }
 946            if let Some(clicked_state) = element_state.clicked_state.as_ref() {
 947                *clicked_state.borrow_mut() = ElementClickedState::default();
 948            }
 949        }
 950
 951        // Ensure we store a focus handle in our element state if we're focusable.
 952        // If there's an explicit focus handle we're tracking, use that. Otherwise
 953        // create a new handle and store it in the element state, which lives for as
 954        // as frames contain an element with this id.
 955        if self.focusable {
 956            element_state.focus_handle.get_or_insert_with(|| {
 957                self.tracked_focus_handle
 958                    .clone()
 959                    .unwrap_or_else(|| cx.focus_handle())
 960            });
 961        }
 962
 963        if let Some(scroll_handle) = self.scroll_handle.as_ref() {
 964            element_state.scroll_offset = Some(scroll_handle.0.borrow().offset.clone());
 965        }
 966
 967        let style = self.compute_style(None, &mut element_state, cx);
 968        let layout_id = f(style, cx);
 969        (layout_id, element_state)
 970    }
 971
 972    pub fn paint(
 973        &mut self,
 974        bounds: Bounds<Pixels>,
 975        content_size: Size<Pixels>,
 976        element_state: &mut InteractiveElementState,
 977        cx: &mut WindowContext,
 978        f: impl FnOnce(&Style, Point<Pixels>, &mut WindowContext),
 979    ) {
 980        let style = self.compute_style(Some(bounds), element_state, cx);
 981        let z_index = style.z_index.unwrap_or(0);
 982
 983        let paint_hover_group_handler = |cx: &mut WindowContext| {
 984            let hover_group_bounds = self
 985                .group_hover_style
 986                .as_ref()
 987                .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
 988
 989            if let Some(group_bounds) = hover_group_bounds {
 990                let hovered = group_bounds.contains(&cx.mouse_position());
 991                cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
 992                    if phase == DispatchPhase::Capture
 993                        && group_bounds.contains(&event.position) != hovered
 994                    {
 995                        cx.refresh();
 996                    }
 997                });
 998            }
 999        };
1000
1001        if style.visibility == Visibility::Hidden {
1002            cx.with_z_index(z_index, |cx| paint_hover_group_handler(cx));
1003            return;
1004        }
1005
1006        cx.with_z_index(z_index, |cx| {
1007            style.paint(bounds, cx, |cx| {
1008                cx.with_text_style(style.text_style().cloned(), |cx| {
1009                    cx.with_content_mask(style.overflow_mask(bounds, cx.rem_size()), |cx| {
1010                        #[cfg(debug_assertions)]
1011                        if self.element_id.is_some()
1012                            && (style.debug
1013                                || style.debug_below
1014                                || cx.has_global::<crate::DebugBelow>())
1015                            && bounds.contains(&cx.mouse_position())
1016                        {
1017                            const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
1018                            let element_id = format!("{:?}", self.element_id.as_ref().unwrap());
1019                            let str_len = element_id.len();
1020
1021                            let render_debug_text = |cx: &mut WindowContext| {
1022                                if let Some(text) = cx
1023                                    .text_system()
1024                                    .shape_text(
1025                                        element_id.into(),
1026                                        FONT_SIZE,
1027                                        &[cx.text_style().to_run(str_len)],
1028                                        None,
1029                                    )
1030                                    .ok()
1031                                    .and_then(|mut text| text.pop())
1032                                {
1033                                    text.paint(bounds.origin, FONT_SIZE, cx).ok();
1034
1035                                    let text_bounds = crate::Bounds {
1036                                        origin: bounds.origin,
1037                                        size: text.size(FONT_SIZE),
1038                                    };
1039                                    if self.location.is_some()
1040                                        && text_bounds.contains(&cx.mouse_position())
1041                                        && cx.modifiers().command
1042                                    {
1043                                        let command_held = cx.modifiers().command;
1044                                        cx.on_key_event({
1045                                            move |e: &crate::ModifiersChangedEvent, _phase, cx| {
1046                                                if e.modifiers.command != command_held
1047                                                    && text_bounds.contains(&cx.mouse_position())
1048                                                {
1049                                                    cx.refresh();
1050                                                }
1051                                            }
1052                                        });
1053
1054                                        let hovered = bounds.contains(&cx.mouse_position());
1055                                        cx.on_mouse_event(
1056                                            move |event: &MouseMoveEvent, phase, cx| {
1057                                                if phase == DispatchPhase::Capture
1058                                                    && bounds.contains(&event.position) != hovered
1059                                                {
1060                                                    cx.refresh();
1061                                                }
1062                                            },
1063                                        );
1064
1065                                        cx.on_mouse_event({
1066                                            let location = self.location.unwrap();
1067                                            move |e: &crate::MouseDownEvent, phase, cx| {
1068                                                if text_bounds.contains(&e.position)
1069                                                    && phase.capture()
1070                                                {
1071                                                    cx.stop_propagation();
1072                                                    let Ok(dir) = std::env::current_dir() else {
1073                                                        return;
1074                                                    };
1075
1076                                                    eprintln!(
1077                                                        "This element was created at:\n{}:{}:{}",
1078                                                        dir.join(location.file()).to_string_lossy(),
1079                                                        location.line(),
1080                                                        location.column()
1081                                                    );
1082                                                }
1083                                            }
1084                                        });
1085                                        cx.paint_quad(crate::outline(
1086                                            crate::Bounds {
1087                                                origin: bounds.origin
1088                                                    + crate::point(
1089                                                        crate::px(0.),
1090                                                        FONT_SIZE - px(2.),
1091                                                    ),
1092                                                size: crate::Size {
1093                                                    width: text_bounds.size.width,
1094                                                    height: crate::px(1.),
1095                                                },
1096                                            },
1097                                            crate::red(),
1098                                        ))
1099                                    }
1100                                }
1101                            };
1102
1103                            cx.with_z_index(1, |cx| {
1104                                cx.with_text_style(
1105                                    Some(crate::TextStyleRefinement {
1106                                        color: Some(crate::red()),
1107                                        line_height: Some(FONT_SIZE.into()),
1108                                        background_color: Some(crate::white()),
1109                                        ..Default::default()
1110                                    }),
1111                                    render_debug_text,
1112                                )
1113                            });
1114                        }
1115
1116                        let interactive_bounds = InteractiveBounds {
1117                            bounds: bounds.intersect(&cx.content_mask().bounds),
1118                            stacking_order: cx.stacking_order().clone(),
1119                        };
1120
1121                        if self.block_mouse
1122                            || style.background.as_ref().is_some_and(|fill| {
1123                                fill.color().is_some_and(|color| !color.is_transparent())
1124                            })
1125                        {
1126                            cx.add_opaque_layer(interactive_bounds.bounds);
1127                        }
1128
1129                        if !cx.has_active_drag() {
1130                            if let Some(mouse_cursor) = style.mouse_cursor {
1131                                let mouse_position = &cx.mouse_position();
1132                                let hovered =
1133                                    interactive_bounds.visibly_contains(mouse_position, cx);
1134                                if hovered {
1135                                    cx.set_cursor_style(mouse_cursor);
1136                                }
1137                            }
1138                        }
1139
1140                        // If this element can be focused, register a mouse down listener
1141                        // that will automatically transfer focus when hitting the element.
1142                        // This behavior can be suppressed by using `cx.prevent_default()`.
1143                        if let Some(focus_handle) = element_state.focus_handle.clone() {
1144                            cx.on_mouse_event({
1145                                let interactive_bounds = interactive_bounds.clone();
1146                                move |event: &MouseDownEvent, phase, cx| {
1147                                    if phase == DispatchPhase::Bubble
1148                                        && !cx.default_prevented()
1149                                        && interactive_bounds.visibly_contains(&event.position, cx)
1150                                    {
1151                                        cx.focus(&focus_handle);
1152                                        // If there is a parent that is also focusable, prevent it
1153                                        // from transferring focus because we already did so.
1154                                        cx.prevent_default();
1155                                    }
1156                                }
1157                            });
1158                        }
1159
1160                        for listener in self.mouse_down_listeners.drain(..) {
1161                            let interactive_bounds = interactive_bounds.clone();
1162                            cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| {
1163                                listener(event, &interactive_bounds, phase, cx);
1164                            })
1165                        }
1166
1167                        for listener in self.mouse_up_listeners.drain(..) {
1168                            let interactive_bounds = interactive_bounds.clone();
1169                            cx.on_mouse_event(move |event: &MouseUpEvent, phase, cx| {
1170                                listener(event, &interactive_bounds, phase, cx);
1171                            })
1172                        }
1173
1174                        for listener in self.mouse_move_listeners.drain(..) {
1175                            let interactive_bounds = interactive_bounds.clone();
1176                            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1177                                listener(event, &interactive_bounds, phase, cx);
1178                            })
1179                        }
1180
1181                        for listener in self.scroll_wheel_listeners.drain(..) {
1182                            let interactive_bounds = interactive_bounds.clone();
1183                            cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
1184                                listener(event, &interactive_bounds, phase, cx);
1185                            })
1186                        }
1187
1188                        paint_hover_group_handler(cx);
1189
1190                        if self.hover_style.is_some()
1191                            || self.base_style.mouse_cursor.is_some()
1192                            || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
1193                        {
1194                            let bounds = bounds.intersect(&cx.content_mask().bounds);
1195                            let hovered = bounds.contains(&cx.mouse_position());
1196                            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1197                                if phase == DispatchPhase::Capture
1198                                    && bounds.contains(&event.position) != hovered
1199                                {
1200                                    cx.refresh();
1201                                }
1202                            });
1203                        }
1204
1205                        let mut drag_listener = mem::take(&mut self.drag_listener);
1206                        let drop_listeners = mem::take(&mut self.drop_listeners);
1207                        let click_listeners = mem::take(&mut self.click_listeners);
1208                        let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
1209
1210                        if !drop_listeners.is_empty() {
1211                            cx.on_mouse_event({
1212                                let interactive_bounds = interactive_bounds.clone();
1213                                move |event: &MouseUpEvent, phase, cx| {
1214                                    if let Some(drag) = &cx.active_drag {
1215                                        if phase == DispatchPhase::Bubble
1216                                            && interactive_bounds
1217                                                .drag_target_contains(&event.position, cx)
1218                                        {
1219                                            let drag_state_type = drag.value.as_ref().type_id();
1220                                            for (drop_state_type, listener) in &drop_listeners {
1221                                                if *drop_state_type == drag_state_type {
1222                                                    let drag = cx.active_drag.take().expect(
1223                                                        "checked for type drag state type above",
1224                                                    );
1225
1226                                                    let mut can_drop = true;
1227                                                    if let Some(predicate) = &can_drop_predicate {
1228                                                        can_drop =
1229                                                            predicate(drag.value.as_ref(), cx);
1230                                                    }
1231
1232                                                    if can_drop {
1233                                                        listener(drag.value.as_ref(), cx);
1234                                                        cx.refresh();
1235                                                        cx.stop_propagation();
1236                                                    }
1237                                                }
1238                                            }
1239                                        }
1240                                    }
1241                                }
1242                            });
1243                        }
1244
1245                        if !click_listeners.is_empty() || drag_listener.is_some() {
1246                            let pending_mouse_down = element_state
1247                                .pending_mouse_down
1248                                .get_or_insert_with(Default::default)
1249                                .clone();
1250
1251                            let clicked_state = element_state
1252                                .clicked_state
1253                                .get_or_insert_with(Default::default)
1254                                .clone();
1255
1256                            cx.on_mouse_event({
1257                                let interactive_bounds = interactive_bounds.clone();
1258                                let pending_mouse_down = pending_mouse_down.clone();
1259                                move |event: &MouseDownEvent, phase, cx| {
1260                                    if phase == DispatchPhase::Bubble
1261                                        && event.button == MouseButton::Left
1262                                        && interactive_bounds.visibly_contains(&event.position, cx)
1263                                    {
1264                                        *pending_mouse_down.borrow_mut() = Some(event.clone());
1265                                        cx.refresh();
1266                                    }
1267                                }
1268                            });
1269
1270                            cx.on_mouse_event({
1271                                let pending_mouse_down = pending_mouse_down.clone();
1272                                move |event: &MouseMoveEvent, phase, cx| {
1273                                    if phase == DispatchPhase::Capture {
1274                                        return;
1275                                    }
1276
1277                                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
1278                                    if let Some(mouse_down) = pending_mouse_down.clone() {
1279                                        if !cx.has_active_drag()
1280                                            && (event.position - mouse_down.position).magnitude()
1281                                                > DRAG_THRESHOLD
1282                                        {
1283                                            if let Some((drag_value, drag_listener)) =
1284                                                drag_listener.take()
1285                                            {
1286                                                *clicked_state.borrow_mut() =
1287                                                    ElementClickedState::default();
1288                                                let cursor_offset = event.position - bounds.origin;
1289                                                let drag = (drag_listener)(drag_value.as_ref(), cx);
1290                                                cx.active_drag = Some(AnyDrag {
1291                                                    view: drag,
1292                                                    value: drag_value,
1293                                                    cursor_offset,
1294                                                });
1295                                                pending_mouse_down.take();
1296                                                cx.refresh();
1297                                                cx.stop_propagation();
1298                                            }
1299                                        }
1300                                    }
1301                                }
1302                            });
1303
1304                            cx.on_mouse_event({
1305                                let interactive_bounds = interactive_bounds.clone();
1306                                let mut captured_mouse_down = None;
1307                                move |event: &MouseUpEvent, phase, cx| match phase {
1308                                    // Clear the pending mouse down during the capture phase,
1309                                    // so that it happens even if another event handler stops
1310                                    // propagation.
1311                                    DispatchPhase::Capture => {
1312                                        let mut pending_mouse_down =
1313                                            pending_mouse_down.borrow_mut();
1314                                        if pending_mouse_down.is_some() {
1315                                            captured_mouse_down = pending_mouse_down.take();
1316                                            cx.refresh();
1317                                        }
1318                                    }
1319                                    // Fire click handlers during the bubble phase.
1320                                    DispatchPhase::Bubble => {
1321                                        if let Some(mouse_down) = captured_mouse_down.take() {
1322                                            if interactive_bounds
1323                                                .visibly_contains(&event.position, cx)
1324                                            {
1325                                                let mouse_click = ClickEvent {
1326                                                    down: mouse_down,
1327                                                    up: event.clone(),
1328                                                };
1329                                                for listener in &click_listeners {
1330                                                    listener(&mouse_click, cx);
1331                                                }
1332                                            }
1333                                        }
1334                                    }
1335                                }
1336                            });
1337                        }
1338
1339                        if let Some(hover_listener) = self.hover_listener.take() {
1340                            let was_hovered = element_state
1341                                .hover_state
1342                                .get_or_insert_with(Default::default)
1343                                .clone();
1344                            let has_mouse_down = element_state
1345                                .pending_mouse_down
1346                                .get_or_insert_with(Default::default)
1347                                .clone();
1348                            let interactive_bounds = interactive_bounds.clone();
1349
1350                            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1351                                if phase != DispatchPhase::Bubble {
1352                                    return;
1353                                }
1354                                let is_hovered = interactive_bounds
1355                                    .visibly_contains(&event.position, cx)
1356                                    && has_mouse_down.borrow().is_none()
1357                                    && !cx.has_active_drag();
1358                                let mut was_hovered = was_hovered.borrow_mut();
1359
1360                                if is_hovered != *was_hovered {
1361                                    *was_hovered = is_hovered;
1362                                    drop(was_hovered);
1363
1364                                    hover_listener(&is_hovered, cx);
1365                                }
1366                            });
1367                        }
1368
1369                        if let Some(tooltip_builder) = self.tooltip_builder.take() {
1370                            let active_tooltip = element_state
1371                                .active_tooltip
1372                                .get_or_insert_with(Default::default)
1373                                .clone();
1374                            let pending_mouse_down = element_state
1375                                .pending_mouse_down
1376                                .get_or_insert_with(Default::default)
1377                                .clone();
1378                            let interactive_bounds = interactive_bounds.clone();
1379
1380                            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1381                                let is_hovered = interactive_bounds
1382                                    .visibly_contains(&event.position, cx)
1383                                    && pending_mouse_down.borrow().is_none();
1384                                if !is_hovered {
1385                                    active_tooltip.borrow_mut().take();
1386                                    return;
1387                                }
1388
1389                                if phase != DispatchPhase::Bubble {
1390                                    return;
1391                                }
1392
1393                                if active_tooltip.borrow().is_none() {
1394                                    let task = cx.spawn({
1395                                        let active_tooltip = active_tooltip.clone();
1396                                        let tooltip_builder = tooltip_builder.clone();
1397
1398                                        move |mut cx| async move {
1399                                            cx.background_executor().timer(TOOLTIP_DELAY).await;
1400                                            cx.update(|_, cx| {
1401                                                active_tooltip.borrow_mut().replace(
1402                                                    ActiveTooltip {
1403                                                        tooltip: Some(AnyTooltip {
1404                                                            view: tooltip_builder(cx),
1405                                                            cursor_offset: cx.mouse_position(),
1406                                                        }),
1407                                                        _task: None,
1408                                                    },
1409                                                );
1410                                                cx.refresh();
1411                                            })
1412                                            .ok();
1413                                        }
1414                                    });
1415                                    active_tooltip.borrow_mut().replace(ActiveTooltip {
1416                                        tooltip: None,
1417                                        _task: Some(task),
1418                                    });
1419                                }
1420                            });
1421
1422                            let active_tooltip = element_state
1423                                .active_tooltip
1424                                .get_or_insert_with(Default::default)
1425                                .clone();
1426                            cx.on_mouse_event(move |_: &MouseDownEvent, _, _| {
1427                                active_tooltip.borrow_mut().take();
1428                            });
1429
1430                            if let Some(active_tooltip) = element_state
1431                                .active_tooltip
1432                                .get_or_insert_with(Default::default)
1433                                .borrow()
1434                                .as_ref()
1435                            {
1436                                if let Some(tooltip) = active_tooltip.tooltip.clone() {
1437                                    cx.set_tooltip(tooltip);
1438                                }
1439                            }
1440                        }
1441
1442                        let active_state = element_state
1443                            .clicked_state
1444                            .get_or_insert_with(Default::default)
1445                            .clone();
1446                        if active_state.borrow().is_clicked() {
1447                            cx.on_mouse_event(move |_: &MouseUpEvent, phase, cx| {
1448                                if phase == DispatchPhase::Capture {
1449                                    *active_state.borrow_mut() = ElementClickedState::default();
1450                                    cx.refresh();
1451                                }
1452                            });
1453                        } else {
1454                            let active_group_bounds = self
1455                                .group_active_style
1456                                .as_ref()
1457                                .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
1458                            let interactive_bounds = interactive_bounds.clone();
1459                            cx.on_mouse_event(move |down: &MouseDownEvent, phase, cx| {
1460                                if phase == DispatchPhase::Bubble && !cx.default_prevented() {
1461                                    let group = active_group_bounds
1462                                        .map_or(false, |bounds| bounds.contains(&down.position));
1463                                    let element =
1464                                        interactive_bounds.visibly_contains(&down.position, cx);
1465                                    if group || element {
1466                                        *active_state.borrow_mut() =
1467                                            ElementClickedState { group, element };
1468                                        cx.refresh();
1469                                    }
1470                                }
1471                            });
1472                        }
1473
1474                        let overflow = style.overflow;
1475                        if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
1476                            if let Some(scroll_handle) = &self.scroll_handle {
1477                                scroll_handle.0.borrow_mut().overflow = overflow;
1478                            }
1479
1480                            let scroll_offset = element_state
1481                                .scroll_offset
1482                                .get_or_insert_with(Rc::default)
1483                                .clone();
1484                            let line_height = cx.line_height();
1485                            let scroll_max = (content_size - bounds.size).max(&Size::default());
1486                            // Clamp scroll offset in case scroll max is smaller now (e.g., if children
1487                            // were removed or the bounds became larger).
1488                            {
1489                                let mut scroll_offset = scroll_offset.borrow_mut();
1490                                scroll_offset.x = scroll_offset.x.clamp(-scroll_max.width, px(0.));
1491                                scroll_offset.y = scroll_offset.y.clamp(-scroll_max.height, px(0.));
1492                            }
1493
1494                            let interactive_bounds = interactive_bounds.clone();
1495                            cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
1496                                if phase == DispatchPhase::Bubble
1497                                    && interactive_bounds.visibly_contains(&event.position, cx)
1498                                {
1499                                    let mut scroll_offset = scroll_offset.borrow_mut();
1500                                    let old_scroll_offset = *scroll_offset;
1501                                    let delta = event.delta.pixel_delta(line_height);
1502
1503                                    if overflow.x == Overflow::Scroll {
1504                                        let mut delta_x = Pixels::ZERO;
1505                                        if !delta.x.is_zero() {
1506                                            delta_x = delta.x;
1507                                        } else if overflow.y != Overflow::Scroll {
1508                                            delta_x = delta.y;
1509                                        }
1510
1511                                        scroll_offset.x = (scroll_offset.x + delta_x)
1512                                            .clamp(-scroll_max.width, px(0.));
1513                                    }
1514
1515                                    if overflow.y == Overflow::Scroll {
1516                                        let mut delta_y = Pixels::ZERO;
1517                                        if !delta.y.is_zero() {
1518                                            delta_y = delta.y;
1519                                        } else if overflow.x != Overflow::Scroll {
1520                                            delta_y = delta.x;
1521                                        }
1522
1523                                        scroll_offset.y = (scroll_offset.y + delta_y)
1524                                            .clamp(-scroll_max.height, px(0.));
1525                                    }
1526
1527                                    if *scroll_offset != old_scroll_offset {
1528                                        cx.refresh();
1529                                        cx.stop_propagation();
1530                                    }
1531                                }
1532                            });
1533                        }
1534
1535                        if let Some(group) = self.group.clone() {
1536                            GroupBounds::push(group, bounds, cx);
1537                        }
1538
1539                        let scroll_offset = element_state
1540                            .scroll_offset
1541                            .as_ref()
1542                            .map(|scroll_offset| *scroll_offset.borrow());
1543
1544                        let key_down_listeners = mem::take(&mut self.key_down_listeners);
1545                        let key_up_listeners = mem::take(&mut self.key_up_listeners);
1546                        let action_listeners = mem::take(&mut self.action_listeners);
1547                        cx.with_key_dispatch(
1548                            self.key_context.clone(),
1549                            element_state.focus_handle.clone(),
1550                            |_, cx| {
1551                                for listener in key_down_listeners {
1552                                    cx.on_key_event(move |event: &KeyDownEvent, phase, cx| {
1553                                        listener(event, phase, cx);
1554                                    })
1555                                }
1556
1557                                for listener in key_up_listeners {
1558                                    cx.on_key_event(move |event: &KeyUpEvent, phase, cx| {
1559                                        listener(event, phase, cx);
1560                                    })
1561                                }
1562
1563                                for (action_type, listener) in action_listeners {
1564                                    cx.on_action(action_type, listener)
1565                                }
1566
1567                                f(&style, scroll_offset.unwrap_or_default(), cx)
1568                            },
1569                        );
1570
1571                        if let Some(group) = self.group.as_ref() {
1572                            GroupBounds::pop(group, cx);
1573                        }
1574                    });
1575                });
1576            });
1577        });
1578    }
1579
1580    pub fn compute_style(
1581        &self,
1582        bounds: Option<Bounds<Pixels>>,
1583        element_state: &mut InteractiveElementState,
1584        cx: &mut WindowContext,
1585    ) -> Style {
1586        let mut style = Style::default();
1587        style.refine(&self.base_style);
1588
1589        cx.with_z_index(style.z_index.unwrap_or(0), |cx| {
1590            if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
1591                if let Some(in_focus_style) = self.in_focus_style.as_ref() {
1592                    if focus_handle.within_focused(cx) {
1593                        style.refine(in_focus_style);
1594                    }
1595                }
1596
1597                if let Some(focus_style) = self.focus_style.as_ref() {
1598                    if focus_handle.is_focused(cx) {
1599                        style.refine(focus_style);
1600                    }
1601                }
1602            }
1603
1604            if let Some(bounds) = bounds {
1605                let mouse_position = cx.mouse_position();
1606                if !cx.has_active_drag() {
1607                    if let Some(group_hover) = self.group_hover_style.as_ref() {
1608                        if let Some(group_bounds) = GroupBounds::get(&group_hover.group, cx) {
1609                            if group_bounds.contains(&mouse_position)
1610                                && cx.was_top_layer(&mouse_position, cx.stacking_order())
1611                            {
1612                                style.refine(&group_hover.style);
1613                            }
1614                        }
1615                    }
1616
1617                    if let Some(hover_style) = self.hover_style.as_ref() {
1618                        if bounds
1619                            .intersect(&cx.content_mask().bounds)
1620                            .contains(&mouse_position)
1621                            && cx.was_top_layer(&mouse_position, cx.stacking_order())
1622                        {
1623                            style.refine(hover_style);
1624                        }
1625                    }
1626                }
1627
1628                if let Some(drag) = cx.active_drag.take() {
1629                    let mut can_drop = true;
1630                    if let Some(can_drop_predicate) = &self.can_drop_predicate {
1631                        can_drop = can_drop_predicate(drag.value.as_ref(), cx);
1632                    }
1633
1634                    if can_drop {
1635                        for (state_type, group_drag_style) in &self.group_drag_over_styles {
1636                            if let Some(group_bounds) =
1637                                GroupBounds::get(&group_drag_style.group, cx)
1638                            {
1639                                if *state_type == drag.value.as_ref().type_id()
1640                                    && group_bounds.contains(&mouse_position)
1641                                {
1642                                    style.refine(&group_drag_style.style);
1643                                }
1644                            }
1645                        }
1646
1647                        for (state_type, drag_over_style) in &self.drag_over_styles {
1648                            if *state_type == drag.value.as_ref().type_id()
1649                                && bounds
1650                                    .intersect(&cx.content_mask().bounds)
1651                                    .contains(&mouse_position)
1652                                && cx.was_top_layer_under_active_drag(
1653                                    &mouse_position,
1654                                    cx.stacking_order(),
1655                                )
1656                            {
1657                                style.refine(drag_over_style);
1658                            }
1659                        }
1660                    }
1661
1662                    cx.active_drag = Some(drag);
1663                }
1664            }
1665
1666            let clicked_state = element_state
1667                .clicked_state
1668                .get_or_insert_with(Default::default)
1669                .borrow();
1670            if clicked_state.group {
1671                if let Some(group) = self.group_active_style.as_ref() {
1672                    style.refine(&group.style)
1673                }
1674            }
1675
1676            if let Some(active_style) = self.active_style.as_ref() {
1677                if clicked_state.element {
1678                    style.refine(active_style)
1679                }
1680            }
1681        });
1682
1683        style
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 request_layout(
1773        &mut self,
1774        state: Option<Self::State>,
1775        cx: &mut WindowContext,
1776    ) -> (LayoutId, Self::State) {
1777        self.element.request_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 request_layout(
1847        &mut self,
1848        state: Option<Self::State>,
1849        cx: &mut WindowContext,
1850    ) -> (LayoutId, Self::State) {
1851        self.element.request_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 Default for ScrollHandle {
1897    fn default() -> Self {
1898        Self::new()
1899    }
1900}
1901
1902impl ScrollHandle {
1903    pub fn new() -> Self {
1904        Self(Rc::default())
1905    }
1906
1907    pub fn offset(&self) -> Point<Pixels> {
1908        *self.0.borrow().offset.borrow()
1909    }
1910
1911    pub fn top_item(&self) -> usize {
1912        let state = self.0.borrow();
1913        let top = state.bounds.top() - state.offset.borrow().y;
1914
1915        match state.child_bounds.binary_search_by(|bounds| {
1916            if top < bounds.top() {
1917                Ordering::Greater
1918            } else if top > bounds.bottom() {
1919                Ordering::Less
1920            } else {
1921                Ordering::Equal
1922            }
1923        }) {
1924            Ok(ix) => ix,
1925            Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
1926        }
1927    }
1928
1929    pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
1930        self.0.borrow().child_bounds.get(ix).cloned()
1931    }
1932
1933    /// scroll_to_item scrolls the minimal amount to ensure that the item is
1934    /// fully visible
1935    pub fn scroll_to_item(&self, ix: usize) {
1936        let state = self.0.borrow();
1937
1938        let Some(bounds) = state.child_bounds.get(ix) else {
1939            return;
1940        };
1941
1942        let mut scroll_offset = state.offset.borrow_mut();
1943
1944        if state.overflow.y == Overflow::Scroll {
1945            if bounds.top() + scroll_offset.y < state.bounds.top() {
1946                scroll_offset.y = state.bounds.top() - bounds.top();
1947            } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
1948                scroll_offset.y = state.bounds.bottom() - bounds.bottom();
1949            }
1950        }
1951
1952        if state.overflow.x == Overflow::Scroll {
1953            if bounds.left() + scroll_offset.x < state.bounds.left() {
1954                scroll_offset.x = state.bounds.left() - bounds.left();
1955            } else if bounds.right() + scroll_offset.x > state.bounds.right() {
1956                scroll_offset.x = state.bounds.right() - bounds.right();
1957            }
1958        }
1959    }
1960
1961    pub fn logical_scroll_top(&self) -> (usize, Pixels) {
1962        let ix = self.top_item();
1963        let state = self.0.borrow();
1964
1965        if let Some(child_bounds) = state.child_bounds.get(ix) {
1966            (
1967                ix,
1968                child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
1969            )
1970        } else {
1971            (ix, px(0.))
1972        }
1973    }
1974
1975    pub fn set_logical_scroll_top(&self, ix: usize, px: Pixels) {
1976        self.0.borrow_mut().requested_scroll_top = Some((ix, px));
1977    }
1978}