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
 982        if style.visibility == Visibility::Hidden {
 983            return;
 984        }
 985
 986        let z_index = style.z_index.unwrap_or(0);
 987        cx.with_z_index(z_index, |cx| {
 988            style.paint(bounds, cx, |cx| {
 989                cx.with_text_style(style.text_style().cloned(), |cx| {
 990                    cx.with_content_mask(style.overflow_mask(bounds, cx.rem_size()), |cx| {
 991                        #[cfg(debug_assertions)]
 992                        if self.element_id.is_some()
 993                            && (style.debug
 994                                || style.debug_below
 995                                || cx.has_global::<crate::DebugBelow>())
 996                            && bounds.contains(&cx.mouse_position())
 997                        {
 998                            const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
 999                            let element_id = format!("{:?}", self.element_id.as_ref().unwrap());
1000                            let str_len = element_id.len();
1001
1002                            let render_debug_text = |cx: &mut WindowContext| {
1003                                if let Some(text) = cx
1004                                    .text_system()
1005                                    .shape_text(
1006                                        element_id.into(),
1007                                        FONT_SIZE,
1008                                        &[cx.text_style().to_run(str_len)],
1009                                        None,
1010                                    )
1011                                    .ok()
1012                                    .and_then(|mut text| text.pop())
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                                            move |e: &crate::ModifiersChangedEvent, _phase, cx| {
1027                                                if e.modifiers.command != command_held
1028                                                    && text_bounds.contains(&cx.mouse_position())
1029                                                {
1030                                                    cx.notify();
1031                                                }
1032                                            }
1033                                        });
1034
1035                                        let hovered = bounds.contains(&cx.mouse_position());
1036                                        cx.on_mouse_event(
1037                                            move |event: &MouseMoveEvent, phase, cx| {
1038                                                if phase == DispatchPhase::Capture
1039                                                    && bounds.contains(&event.position) != hovered
1040                                                {
1041                                                    cx.notify();
1042                                                }
1043                                            },
1044                                        );
1045
1046                                        cx.on_mouse_event({
1047                                            let location = self.location.unwrap();
1048                                            move |e: &crate::MouseDownEvent, phase, cx| {
1049                                                if text_bounds.contains(&e.position)
1050                                                    && phase.capture()
1051                                                {
1052                                                    cx.stop_propagation();
1053                                                    let Ok(dir) = std::env::current_dir() else {
1054                                                        return;
1055                                                    };
1056
1057                                                    eprintln!(
1058                                                        "This element was created at:\n{}:{}:{}",
1059                                                        dir.join(location.file()).to_string_lossy(),
1060                                                        location.line(),
1061                                                        location.column()
1062                                                    );
1063                                                }
1064                                            }
1065                                        });
1066                                        cx.paint_quad(crate::outline(
1067                                            crate::Bounds {
1068                                                origin: bounds.origin
1069                                                    + crate::point(
1070                                                        crate::px(0.),
1071                                                        FONT_SIZE - px(2.),
1072                                                    ),
1073                                                size: crate::Size {
1074                                                    width: text_bounds.size.width,
1075                                                    height: crate::px(1.),
1076                                                },
1077                                            },
1078                                            crate::red(),
1079                                        ))
1080                                    }
1081                                }
1082                            };
1083
1084                            cx.with_z_index(1, |cx| {
1085                                cx.with_text_style(
1086                                    Some(crate::TextStyleRefinement {
1087                                        color: Some(crate::red()),
1088                                        line_height: Some(FONT_SIZE.into()),
1089                                        background_color: Some(crate::white()),
1090                                        ..Default::default()
1091                                    }),
1092                                    render_debug_text,
1093                                )
1094                            });
1095                        }
1096
1097                        let interactive_bounds = InteractiveBounds {
1098                            bounds: bounds.intersect(&cx.content_mask().bounds),
1099                            stacking_order: cx.stacking_order().clone(),
1100                        };
1101
1102                        if self.block_mouse
1103                            || style.background.as_ref().is_some_and(|fill| {
1104                                fill.color().is_some_and(|color| !color.is_transparent())
1105                            })
1106                        {
1107                            cx.add_opaque_layer(interactive_bounds.bounds);
1108                        }
1109
1110                        if !cx.has_active_drag() {
1111                            if let Some(mouse_cursor) = style.mouse_cursor {
1112                                let mouse_position = &cx.mouse_position();
1113                                let hovered =
1114                                    interactive_bounds.visibly_contains(mouse_position, cx);
1115                                if hovered {
1116                                    cx.set_cursor_style(mouse_cursor);
1117                                }
1118                            }
1119                        }
1120
1121                        // If this element can be focused, register a mouse down listener
1122                        // that will automatically transfer focus when hitting the element.
1123                        // This behavior can be suppressed by using `cx.prevent_default()`.
1124                        if let Some(focus_handle) = element_state.focus_handle.clone() {
1125                            cx.on_mouse_event({
1126                                let interactive_bounds = interactive_bounds.clone();
1127                                move |event: &MouseDownEvent, phase, cx| {
1128                                    if phase == DispatchPhase::Bubble
1129                                        && !cx.default_prevented()
1130                                        && interactive_bounds.visibly_contains(&event.position, cx)
1131                                    {
1132                                        cx.focus(&focus_handle);
1133                                        // If there is a parent that is also focusable, prevent it
1134                                        // from transferring focus because we already did so.
1135                                        cx.prevent_default();
1136                                    }
1137                                }
1138                            });
1139                        }
1140
1141                        for listener in self.mouse_down_listeners.drain(..) {
1142                            let interactive_bounds = interactive_bounds.clone();
1143                            cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| {
1144                                listener(event, &interactive_bounds, phase, cx);
1145                            })
1146                        }
1147
1148                        for listener in self.mouse_up_listeners.drain(..) {
1149                            let interactive_bounds = interactive_bounds.clone();
1150                            cx.on_mouse_event(move |event: &MouseUpEvent, phase, cx| {
1151                                listener(event, &interactive_bounds, phase, cx);
1152                            })
1153                        }
1154
1155                        for listener in self.mouse_move_listeners.drain(..) {
1156                            let interactive_bounds = interactive_bounds.clone();
1157                            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1158                                listener(event, &interactive_bounds, phase, cx);
1159                            })
1160                        }
1161
1162                        for listener in self.scroll_wheel_listeners.drain(..) {
1163                            let interactive_bounds = interactive_bounds.clone();
1164                            cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
1165                                listener(event, &interactive_bounds, phase, cx);
1166                            })
1167                        }
1168
1169                        let hover_group_bounds = self
1170                            .group_hover_style
1171                            .as_ref()
1172                            .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
1173
1174                        if let Some(group_bounds) = hover_group_bounds {
1175                            let hovered = group_bounds.contains(&cx.mouse_position());
1176                            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1177                                if phase == DispatchPhase::Capture
1178                                    && group_bounds.contains(&event.position) != hovered
1179                                {
1180                                    cx.notify();
1181                                }
1182                            });
1183                        }
1184
1185                        if self.hover_style.is_some()
1186                            || self.base_style.mouse_cursor.is_some()
1187                            || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
1188                        {
1189                            let bounds = bounds.intersect(&cx.content_mask().bounds);
1190                            let hovered = bounds.contains(&cx.mouse_position());
1191                            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1192                                if phase == DispatchPhase::Capture
1193                                    && bounds.contains(&event.position) != hovered
1194                                {
1195                                    cx.notify();
1196                                }
1197                            });
1198                        }
1199
1200                        let mut drag_listener = mem::take(&mut self.drag_listener);
1201                        let drop_listeners = mem::take(&mut self.drop_listeners);
1202                        let click_listeners = mem::take(&mut self.click_listeners);
1203                        let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
1204
1205                        if !drop_listeners.is_empty() {
1206                            cx.on_mouse_event({
1207                                let interactive_bounds = interactive_bounds.clone();
1208                                move |event: &MouseUpEvent, phase, cx| {
1209                                    if let Some(drag) = &cx.active_drag {
1210                                        if phase == DispatchPhase::Bubble
1211                                            && interactive_bounds
1212                                                .drag_target_contains(&event.position, cx)
1213                                        {
1214                                            let drag_state_type = drag.value.as_ref().type_id();
1215                                            for (drop_state_type, listener) in &drop_listeners {
1216                                                if *drop_state_type == drag_state_type {
1217                                                    let drag = cx.active_drag.take().expect(
1218                                                        "checked for type drag state type above",
1219                                                    );
1220
1221                                                    let mut can_drop = true;
1222                                                    if let Some(predicate) = &can_drop_predicate {
1223                                                        can_drop =
1224                                                            predicate(drag.value.as_ref(), cx);
1225                                                    }
1226
1227                                                    if can_drop {
1228                                                        listener(drag.value.as_ref(), cx);
1229                                                        cx.notify();
1230                                                        cx.stop_propagation();
1231                                                    }
1232                                                }
1233                                            }
1234                                        }
1235                                    }
1236                                }
1237                            });
1238                        }
1239
1240                        if !click_listeners.is_empty() || drag_listener.is_some() {
1241                            let pending_mouse_down = element_state
1242                                .pending_mouse_down
1243                                .get_or_insert_with(Default::default)
1244                                .clone();
1245
1246                            let clicked_state = element_state
1247                                .clicked_state
1248                                .get_or_insert_with(Default::default)
1249                                .clone();
1250
1251                            cx.on_mouse_event({
1252                                let interactive_bounds = interactive_bounds.clone();
1253                                let pending_mouse_down = pending_mouse_down.clone();
1254                                move |event: &MouseDownEvent, phase, cx| {
1255                                    if phase == DispatchPhase::Bubble
1256                                        && event.button == MouseButton::Left
1257                                        && interactive_bounds.visibly_contains(&event.position, cx)
1258                                    {
1259                                        *pending_mouse_down.borrow_mut() = Some(event.clone());
1260                                        cx.notify();
1261                                    }
1262                                }
1263                            });
1264
1265                            cx.on_mouse_event({
1266                                let pending_mouse_down = pending_mouse_down.clone();
1267                                move |event: &MouseMoveEvent, phase, cx| {
1268                                    if phase == DispatchPhase::Capture {
1269                                        return;
1270                                    }
1271
1272                                    let mut pending_mouse_down = pending_mouse_down.borrow_mut();
1273                                    if let Some(mouse_down) = pending_mouse_down.clone() {
1274                                        if !cx.has_active_drag()
1275                                            && (event.position - mouse_down.position).magnitude()
1276                                                > DRAG_THRESHOLD
1277                                        {
1278                                            if let Some((drag_value, drag_listener)) =
1279                                                drag_listener.take()
1280                                            {
1281                                                *clicked_state.borrow_mut() =
1282                                                    ElementClickedState::default();
1283                                                let cursor_offset = event.position - bounds.origin;
1284                                                let drag = (drag_listener)(drag_value.as_ref(), cx);
1285                                                cx.active_drag = Some(AnyDrag {
1286                                                    view: drag,
1287                                                    value: drag_value,
1288                                                    cursor_offset,
1289                                                });
1290                                                pending_mouse_down.take();
1291                                                cx.notify();
1292                                                cx.stop_propagation();
1293                                            }
1294                                        }
1295                                    }
1296                                }
1297                            });
1298
1299                            cx.on_mouse_event({
1300                                let interactive_bounds = interactive_bounds.clone();
1301                                let mut captured_mouse_down = None;
1302                                move |event: &MouseUpEvent, phase, cx| match phase {
1303                                    // Clear the pending mouse down during the capture phase,
1304                                    // so that it happens even if another event handler stops
1305                                    // propagation.
1306                                    DispatchPhase::Capture => {
1307                                        let mut pending_mouse_down =
1308                                            pending_mouse_down.borrow_mut();
1309                                        if pending_mouse_down.is_some() {
1310                                            captured_mouse_down = pending_mouse_down.take();
1311                                            cx.notify();
1312                                        }
1313                                    }
1314                                    // Fire click handlers during the bubble phase.
1315                                    DispatchPhase::Bubble => {
1316                                        if let Some(mouse_down) = captured_mouse_down.take() {
1317                                            if interactive_bounds
1318                                                .visibly_contains(&event.position, cx)
1319                                            {
1320                                                let mouse_click = ClickEvent {
1321                                                    down: mouse_down,
1322                                                    up: event.clone(),
1323                                                };
1324                                                for listener in &click_listeners {
1325                                                    listener(&mouse_click, cx);
1326                                                }
1327                                            }
1328                                        }
1329                                    }
1330                                }
1331                            });
1332                        }
1333
1334                        if let Some(hover_listener) = self.hover_listener.take() {
1335                            let was_hovered = element_state
1336                                .hover_state
1337                                .get_or_insert_with(Default::default)
1338                                .clone();
1339                            let has_mouse_down = element_state
1340                                .pending_mouse_down
1341                                .get_or_insert_with(Default::default)
1342                                .clone();
1343                            let interactive_bounds = interactive_bounds.clone();
1344
1345                            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1346                                if phase != DispatchPhase::Bubble {
1347                                    return;
1348                                }
1349                                let is_hovered = interactive_bounds
1350                                    .visibly_contains(&event.position, cx)
1351                                    && has_mouse_down.borrow().is_none()
1352                                    && !cx.has_active_drag();
1353                                let mut was_hovered = was_hovered.borrow_mut();
1354
1355                                if is_hovered != *was_hovered {
1356                                    *was_hovered = is_hovered;
1357                                    drop(was_hovered);
1358
1359                                    hover_listener(&is_hovered, cx);
1360                                }
1361                            });
1362                        }
1363
1364                        if let Some(tooltip_builder) = self.tooltip_builder.take() {
1365                            let active_tooltip = element_state
1366                                .active_tooltip
1367                                .get_or_insert_with(Default::default)
1368                                .clone();
1369                            let pending_mouse_down = element_state
1370                                .pending_mouse_down
1371                                .get_or_insert_with(Default::default)
1372                                .clone();
1373                            let interactive_bounds = interactive_bounds.clone();
1374
1375                            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1376                                let is_hovered = interactive_bounds
1377                                    .visibly_contains(&event.position, cx)
1378                                    && pending_mouse_down.borrow().is_none();
1379                                if !is_hovered {
1380                                    active_tooltip.borrow_mut().take();
1381                                    return;
1382                                }
1383
1384                                if phase != DispatchPhase::Bubble {
1385                                    return;
1386                                }
1387
1388                                if active_tooltip.borrow().is_none() {
1389                                    let task = cx.spawn({
1390                                        let active_tooltip = active_tooltip.clone();
1391                                        let tooltip_builder = tooltip_builder.clone();
1392
1393                                        move |mut cx| async move {
1394                                            cx.background_executor().timer(TOOLTIP_DELAY).await;
1395                                            cx.update(|_, cx| {
1396                                                active_tooltip.borrow_mut().replace(
1397                                                    ActiveTooltip {
1398                                                        tooltip: Some(AnyTooltip {
1399                                                            view: tooltip_builder(cx),
1400                                                            cursor_offset: cx.mouse_position(),
1401                                                        }),
1402                                                        _task: None,
1403                                                    },
1404                                                );
1405                                                cx.notify();
1406                                            })
1407                                            .ok();
1408                                        }
1409                                    });
1410                                    active_tooltip.borrow_mut().replace(ActiveTooltip {
1411                                        tooltip: None,
1412                                        _task: Some(task),
1413                                    });
1414                                }
1415                            });
1416
1417                            let active_tooltip = element_state
1418                                .active_tooltip
1419                                .get_or_insert_with(Default::default)
1420                                .clone();
1421                            cx.on_mouse_event(move |_: &MouseDownEvent, _, _| {
1422                                active_tooltip.borrow_mut().take();
1423                            });
1424
1425                            if let Some(active_tooltip) = element_state
1426                                .active_tooltip
1427                                .get_or_insert_with(Default::default)
1428                                .borrow()
1429                                .as_ref()
1430                            {
1431                                if active_tooltip.tooltip.is_some() {
1432                                    cx.active_tooltip = active_tooltip.tooltip.clone()
1433                                }
1434                            }
1435                        }
1436
1437                        let active_state = element_state
1438                            .clicked_state
1439                            .get_or_insert_with(Default::default)
1440                            .clone();
1441                        if active_state.borrow().is_clicked() {
1442                            cx.on_mouse_event(move |_: &MouseUpEvent, phase, cx| {
1443                                if phase == DispatchPhase::Capture {
1444                                    *active_state.borrow_mut() = ElementClickedState::default();
1445                                    cx.notify();
1446                                }
1447                            });
1448                        } else {
1449                            let active_group_bounds = self
1450                                .group_active_style
1451                                .as_ref()
1452                                .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
1453                            let interactive_bounds = interactive_bounds.clone();
1454                            cx.on_mouse_event(move |down: &MouseDownEvent, phase, cx| {
1455                                if phase == DispatchPhase::Bubble && !cx.default_prevented() {
1456                                    let group = active_group_bounds
1457                                        .map_or(false, |bounds| bounds.contains(&down.position));
1458                                    let element =
1459                                        interactive_bounds.visibly_contains(&down.position, cx);
1460                                    if group || element {
1461                                        *active_state.borrow_mut() =
1462                                            ElementClickedState { group, element };
1463                                        cx.notify();
1464                                    }
1465                                }
1466                            });
1467                        }
1468
1469                        let overflow = style.overflow;
1470                        if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
1471                            if let Some(scroll_handle) = &self.scroll_handle {
1472                                scroll_handle.0.borrow_mut().overflow = overflow;
1473                            }
1474
1475                            let scroll_offset = element_state
1476                                .scroll_offset
1477                                .get_or_insert_with(Rc::default)
1478                                .clone();
1479                            let line_height = cx.line_height();
1480                            let scroll_max = (content_size - bounds.size).max(&Size::default());
1481                            // Clamp scroll offset in case scroll max is smaller now (e.g., if children
1482                            // were removed or the bounds became larger).
1483                            {
1484                                let mut scroll_offset = scroll_offset.borrow_mut();
1485                                scroll_offset.x = scroll_offset.x.clamp(-scroll_max.width, px(0.));
1486                                scroll_offset.y = scroll_offset.y.clamp(-scroll_max.height, px(0.));
1487                            }
1488
1489                            let interactive_bounds = interactive_bounds.clone();
1490                            cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
1491                                if phase == DispatchPhase::Bubble
1492                                    && interactive_bounds.visibly_contains(&event.position, cx)
1493                                {
1494                                    let mut scroll_offset = scroll_offset.borrow_mut();
1495                                    let old_scroll_offset = *scroll_offset;
1496                                    let delta = event.delta.pixel_delta(line_height);
1497
1498                                    if overflow.x == Overflow::Scroll {
1499                                        let mut delta_x = Pixels::ZERO;
1500                                        if !delta.x.is_zero() {
1501                                            delta_x = delta.x;
1502                                        } else if overflow.y != Overflow::Scroll {
1503                                            delta_x = delta.y;
1504                                        }
1505
1506                                        scroll_offset.x = (scroll_offset.x + delta_x)
1507                                            .clamp(-scroll_max.width, px(0.));
1508                                    }
1509
1510                                    if overflow.y == Overflow::Scroll {
1511                                        let mut delta_y = Pixels::ZERO;
1512                                        if !delta.y.is_zero() {
1513                                            delta_y = delta.y;
1514                                        } else if overflow.x != Overflow::Scroll {
1515                                            delta_y = delta.x;
1516                                        }
1517
1518                                        scroll_offset.y = (scroll_offset.y + delta_y)
1519                                            .clamp(-scroll_max.height, px(0.));
1520                                    }
1521
1522                                    if *scroll_offset != old_scroll_offset {
1523                                        cx.notify();
1524                                        cx.stop_propagation();
1525                                    }
1526                                }
1527                            });
1528                        }
1529
1530                        if let Some(group) = self.group.clone() {
1531                            GroupBounds::push(group, bounds, cx);
1532                        }
1533
1534                        let scroll_offset = element_state
1535                            .scroll_offset
1536                            .as_ref()
1537                            .map(|scroll_offset| *scroll_offset.borrow());
1538
1539                        let key_down_listeners = mem::take(&mut self.key_down_listeners);
1540                        let key_up_listeners = mem::take(&mut self.key_up_listeners);
1541                        let action_listeners = mem::take(&mut self.action_listeners);
1542                        cx.with_key_dispatch(
1543                            self.key_context.clone(),
1544                            element_state.focus_handle.clone(),
1545                            |_, cx| {
1546                                for listener in key_down_listeners {
1547                                    cx.on_key_event(move |event: &KeyDownEvent, phase, cx| {
1548                                        listener(event, phase, cx);
1549                                    })
1550                                }
1551
1552                                for listener in key_up_listeners {
1553                                    cx.on_key_event(move |event: &KeyUpEvent, phase, cx| {
1554                                        listener(event, phase, cx);
1555                                    })
1556                                }
1557
1558                                for (action_type, listener) in action_listeners {
1559                                    cx.on_action(action_type, listener)
1560                                }
1561
1562                                f(&style, scroll_offset.unwrap_or_default(), cx)
1563                            },
1564                        );
1565
1566                        if let Some(group) = self.group.as_ref() {
1567                            GroupBounds::pop(group, cx);
1568                        }
1569                    });
1570                });
1571            });
1572        });
1573    }
1574
1575    pub fn compute_style(
1576        &self,
1577        bounds: Option<Bounds<Pixels>>,
1578        element_state: &mut InteractiveElementState,
1579        cx: &mut WindowContext,
1580    ) -> Style {
1581        let mut style = Style::default();
1582        style.refine(&self.base_style);
1583
1584        cx.with_z_index(style.z_index.unwrap_or(0), |cx| {
1585            if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
1586                if let Some(in_focus_style) = self.in_focus_style.as_ref() {
1587                    if focus_handle.within_focused(cx) {
1588                        style.refine(in_focus_style);
1589                    }
1590                }
1591
1592                if let Some(focus_style) = self.focus_style.as_ref() {
1593                    if focus_handle.is_focused(cx) {
1594                        style.refine(focus_style);
1595                    }
1596                }
1597            }
1598
1599            if let Some(bounds) = bounds {
1600                let mouse_position = cx.mouse_position();
1601                if !cx.has_active_drag() {
1602                    if let Some(group_hover) = self.group_hover_style.as_ref() {
1603                        if let Some(group_bounds) = GroupBounds::get(&group_hover.group, cx) {
1604                            if group_bounds.contains(&mouse_position)
1605                                && cx.was_top_layer(&mouse_position, cx.stacking_order())
1606                            {
1607                                style.refine(&group_hover.style);
1608                            }
1609                        }
1610                    }
1611
1612                    if let Some(hover_style) = self.hover_style.as_ref() {
1613                        if bounds
1614                            .intersect(&cx.content_mask().bounds)
1615                            .contains(&mouse_position)
1616                            && cx.was_top_layer(&mouse_position, cx.stacking_order())
1617                        {
1618                            style.refine(hover_style);
1619                        }
1620                    }
1621                }
1622
1623                if let Some(drag) = cx.active_drag.take() {
1624                    let mut can_drop = true;
1625                    if let Some(can_drop_predicate) = &self.can_drop_predicate {
1626                        can_drop = can_drop_predicate(drag.value.as_ref(), cx);
1627                    }
1628
1629                    if can_drop {
1630                        for (state_type, group_drag_style) in &self.group_drag_over_styles {
1631                            if let Some(group_bounds) =
1632                                GroupBounds::get(&group_drag_style.group, cx)
1633                            {
1634                                if *state_type == drag.value.as_ref().type_id()
1635                                    && group_bounds.contains(&mouse_position)
1636                                {
1637                                    style.refine(&group_drag_style.style);
1638                                }
1639                            }
1640                        }
1641
1642                        for (state_type, drag_over_style) in &self.drag_over_styles {
1643                            if *state_type == drag.value.as_ref().type_id()
1644                                && bounds
1645                                    .intersect(&cx.content_mask().bounds)
1646                                    .contains(&mouse_position)
1647                                && cx.was_top_layer_under_active_drag(
1648                                    &mouse_position,
1649                                    cx.stacking_order(),
1650                                )
1651                            {
1652                                style.refine(drag_over_style);
1653                            }
1654                        }
1655                    }
1656
1657                    cx.active_drag = Some(drag);
1658                }
1659            }
1660
1661            let clicked_state = element_state
1662                .clicked_state
1663                .get_or_insert_with(Default::default)
1664                .borrow();
1665            if clicked_state.group {
1666                if let Some(group) = self.group_active_style.as_ref() {
1667                    style.refine(&group.style)
1668                }
1669            }
1670
1671            if let Some(active_style) = self.active_style.as_ref() {
1672                if clicked_state.element {
1673                    style.refine(active_style)
1674                }
1675            }
1676        });
1677
1678        style
1679    }
1680}
1681
1682#[derive(Default)]
1683pub struct InteractiveElementState {
1684    pub focus_handle: Option<FocusHandle>,
1685    pub clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
1686    pub hover_state: Option<Rc<RefCell<bool>>>,
1687    pub pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
1688    pub scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
1689    pub active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
1690}
1691
1692pub struct ActiveTooltip {
1693    tooltip: Option<AnyTooltip>,
1694    _task: Option<Task<()>>,
1695}
1696
1697/// Whether or not the element or a group that contains it is clicked by the mouse.
1698#[derive(Copy, Clone, Default, Eq, PartialEq)]
1699pub struct ElementClickedState {
1700    pub group: bool,
1701    pub element: bool,
1702}
1703
1704impl ElementClickedState {
1705    fn is_clicked(&self) -> bool {
1706        self.group || self.element
1707    }
1708}
1709
1710#[derive(Default)]
1711pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
1712
1713impl GroupBounds {
1714    pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
1715        cx.default_global::<Self>()
1716            .0
1717            .get(name)
1718            .and_then(|bounds_stack| bounds_stack.last())
1719            .cloned()
1720    }
1721
1722    pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
1723        cx.default_global::<Self>()
1724            .0
1725            .entry(name)
1726            .or_default()
1727            .push(bounds);
1728    }
1729
1730    pub fn pop(name: &SharedString, cx: &mut AppContext) {
1731        cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
1732    }
1733}
1734
1735pub struct Focusable<E> {
1736    pub element: E,
1737}
1738
1739impl<E: InteractiveElement> FocusableElement for Focusable<E> {}
1740
1741impl<E> InteractiveElement for Focusable<E>
1742where
1743    E: InteractiveElement,
1744{
1745    fn interactivity(&mut self) -> &mut Interactivity {
1746        self.element.interactivity()
1747    }
1748}
1749
1750impl<E: StatefulInteractiveElement> StatefulInteractiveElement for Focusable<E> {}
1751
1752impl<E> Styled for Focusable<E>
1753where
1754    E: Styled,
1755{
1756    fn style(&mut self) -> &mut StyleRefinement {
1757        self.element.style()
1758    }
1759}
1760
1761impl<E> Element for Focusable<E>
1762where
1763    E: Element,
1764{
1765    type State = E::State;
1766
1767    fn request_layout(
1768        &mut self,
1769        state: Option<Self::State>,
1770        cx: &mut WindowContext,
1771    ) -> (LayoutId, Self::State) {
1772        self.element.request_layout(state, cx)
1773    }
1774
1775    fn paint(&mut self, bounds: Bounds<Pixels>, state: &mut Self::State, cx: &mut WindowContext) {
1776        self.element.paint(bounds, state, cx)
1777    }
1778}
1779
1780impl<E> IntoElement for Focusable<E>
1781where
1782    E: IntoElement,
1783{
1784    type Element = E::Element;
1785
1786    fn element_id(&self) -> Option<ElementId> {
1787        self.element.element_id()
1788    }
1789
1790    fn into_element(self) -> Self::Element {
1791        self.element.into_element()
1792    }
1793}
1794
1795impl<E> ParentElement for Focusable<E>
1796where
1797    E: ParentElement,
1798{
1799    fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> {
1800        self.element.children_mut()
1801    }
1802}
1803
1804pub struct Stateful<E> {
1805    element: E,
1806}
1807
1808impl<E> Styled for Stateful<E>
1809where
1810    E: Styled,
1811{
1812    fn style(&mut self) -> &mut StyleRefinement {
1813        self.element.style()
1814    }
1815}
1816
1817impl<E> StatefulInteractiveElement for Stateful<E>
1818where
1819    E: Element,
1820    Self: InteractiveElement,
1821{
1822}
1823
1824impl<E> InteractiveElement for Stateful<E>
1825where
1826    E: InteractiveElement,
1827{
1828    fn interactivity(&mut self) -> &mut Interactivity {
1829        self.element.interactivity()
1830    }
1831}
1832
1833impl<E: FocusableElement> FocusableElement for Stateful<E> {}
1834
1835impl<E> Element for Stateful<E>
1836where
1837    E: Element,
1838{
1839    type State = E::State;
1840
1841    fn request_layout(
1842        &mut self,
1843        state: Option<Self::State>,
1844        cx: &mut WindowContext,
1845    ) -> (LayoutId, Self::State) {
1846        self.element.request_layout(state, cx)
1847    }
1848
1849    fn paint(&mut self, bounds: Bounds<Pixels>, state: &mut Self::State, cx: &mut WindowContext) {
1850        self.element.paint(bounds, state, cx)
1851    }
1852}
1853
1854impl<E> IntoElement for Stateful<E>
1855where
1856    E: Element,
1857{
1858    type Element = Self;
1859
1860    fn element_id(&self) -> Option<ElementId> {
1861        self.element.element_id()
1862    }
1863
1864    fn into_element(self) -> Self::Element {
1865        self
1866    }
1867}
1868
1869impl<E> ParentElement for Stateful<E>
1870where
1871    E: ParentElement,
1872{
1873    fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> {
1874        self.element.children_mut()
1875    }
1876}
1877
1878#[derive(Default)]
1879struct ScrollHandleState {
1880    // not great to have the nested rc's...
1881    offset: Rc<RefCell<Point<Pixels>>>,
1882    bounds: Bounds<Pixels>,
1883    child_bounds: Vec<Bounds<Pixels>>,
1884    requested_scroll_top: Option<(usize, Pixels)>,
1885    overflow: Point<Overflow>,
1886}
1887
1888#[derive(Clone)]
1889pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
1890
1891impl Default for ScrollHandle {
1892    fn default() -> Self {
1893        Self::new()
1894    }
1895}
1896
1897impl ScrollHandle {
1898    pub fn new() -> Self {
1899        Self(Rc::default())
1900    }
1901
1902    pub fn offset(&self) -> Point<Pixels> {
1903        *self.0.borrow().offset.borrow()
1904    }
1905
1906    pub fn top_item(&self) -> usize {
1907        let state = self.0.borrow();
1908        let top = state.bounds.top() - state.offset.borrow().y;
1909
1910        match state.child_bounds.binary_search_by(|bounds| {
1911            if top < bounds.top() {
1912                Ordering::Greater
1913            } else if top > bounds.bottom() {
1914                Ordering::Less
1915            } else {
1916                Ordering::Equal
1917            }
1918        }) {
1919            Ok(ix) => ix,
1920            Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
1921        }
1922    }
1923
1924    pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
1925        self.0.borrow().child_bounds.get(ix).cloned()
1926    }
1927
1928    /// scroll_to_item scrolls the minimal amount to ensure that the item is
1929    /// fully visible
1930    pub fn scroll_to_item(&self, ix: usize) {
1931        let state = self.0.borrow();
1932
1933        let Some(bounds) = state.child_bounds.get(ix) else {
1934            return;
1935        };
1936
1937        let mut scroll_offset = state.offset.borrow_mut();
1938
1939        if state.overflow.y == Overflow::Scroll {
1940            if bounds.top() + scroll_offset.y < state.bounds.top() {
1941                scroll_offset.y = state.bounds.top() - bounds.top();
1942            } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
1943                scroll_offset.y = state.bounds.bottom() - bounds.bottom();
1944            }
1945        }
1946
1947        if state.overflow.x == Overflow::Scroll {
1948            if bounds.left() + scroll_offset.x < state.bounds.left() {
1949                scroll_offset.x = state.bounds.left() - bounds.left();
1950            } else if bounds.right() + scroll_offset.x > state.bounds.right() {
1951                scroll_offset.x = state.bounds.right() - bounds.right();
1952            }
1953        }
1954    }
1955
1956    pub fn logical_scroll_top(&self) -> (usize, Pixels) {
1957        let ix = self.top_item();
1958        let state = self.0.borrow();
1959
1960        if let Some(child_bounds) = state.child_bounds.get(ix) {
1961            (
1962                ix,
1963                child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
1964            )
1965        } else {
1966            (ix, px(0.))
1967        }
1968    }
1969
1970    pub fn set_logical_scroll_top(&self, ix: usize, px: Pixels) {
1971        self.0.borrow_mut().requested_scroll_top = Some((ix, px));
1972    }
1973}