div.rs

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