node.rs

   1use crate::{
   2    point, px, Action, AnyDrag, AnyElement, AnyTooltip, AnyView, AppContext, BorrowAppContext,
   3    BorrowWindow, Bounds, ClickEvent, DispatchPhase, Element, ElementId, FocusHandle, KeyContext,
   4    KeyDownEvent, KeyUpEvent, LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
   5    Pixels, Point, Render, ScrollWheelEvent, SharedString, Size, Style, StyleRefinement, Styled,
   6    Task, View, ViewContext, Visibility,
   7};
   8use collections::HashMap;
   9use parking_lot::Mutex;
  10use refineable::Refineable;
  11use smallvec::SmallVec;
  12use std::{
  13    any::{Any, TypeId},
  14    marker::PhantomData,
  15    mem,
  16    sync::Arc,
  17    time::Duration,
  18};
  19use taffy::style::Overflow;
  20
  21const DRAG_THRESHOLD: f64 = 2.;
  22const TOOLTIP_DELAY: Duration = Duration::from_millis(500);
  23const TOOLTIP_OFFSET: Point<Pixels> = Point::new(px(10.0), px(8.0));
  24
  25pub struct GroupStyle {
  26    pub group: SharedString,
  27    pub style: StyleRefinement,
  28}
  29
  30pub trait InteractiveComponent<V: 'static>: Sized + Element<V> {
  31    fn interactivity(&mut self) -> &mut Interactivity<V>;
  32
  33    fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
  34    where
  35        Self: Sized,
  36    {
  37        self.interactivity().hover_style = f(StyleRefinement::default());
  38        self
  39    }
  40
  41    fn group_hover(
  42        mut self,
  43        group_name: impl Into<SharedString>,
  44        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
  45    ) -> Self
  46    where
  47        Self: Sized,
  48    {
  49        self.interactivity().group_hover_style = Some(GroupStyle {
  50            group: group_name.into(),
  51            style: f(StyleRefinement::default()),
  52        });
  53        self
  54    }
  55
  56    fn on_mouse_down(
  57        mut self,
  58        button: MouseButton,
  59        handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + 'static,
  60    ) -> Self
  61    where
  62        Self: Sized,
  63    {
  64        self.interactivity().mouse_down_listeners.push(Box::new(
  65            move |view, event, bounds, phase, cx| {
  66                if phase == DispatchPhase::Bubble
  67                    && event.button == button
  68                    && bounds.contains_point(&event.position)
  69                {
  70                    handler(view, event, cx)
  71                }
  72            },
  73        ));
  74        self
  75    }
  76
  77    fn on_mouse_up(
  78        mut self,
  79        button: MouseButton,
  80        handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + 'static,
  81    ) -> Self
  82    where
  83        Self: Sized,
  84    {
  85        self.interactivity().mouse_up_listeners.push(Box::new(
  86            move |view, event, bounds, phase, cx| {
  87                if phase == DispatchPhase::Bubble
  88                    && event.button == button
  89                    && bounds.contains_point(&event.position)
  90                {
  91                    handler(view, event, cx)
  92                }
  93            },
  94        ));
  95        self
  96    }
  97
  98    fn on_mouse_down_out(
  99        mut self,
 100        handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + 'static,
 101    ) -> Self
 102    where
 103        Self: Sized,
 104    {
 105        self.interactivity().mouse_down_listeners.push(Box::new(
 106            move |view, event, bounds, phase, cx| {
 107                if phase == DispatchPhase::Capture && !bounds.contains_point(&event.position) {
 108                    handler(view, event, cx)
 109                }
 110            },
 111        ));
 112        self
 113    }
 114
 115    fn on_mouse_up_out(
 116        mut self,
 117        button: MouseButton,
 118        handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + 'static,
 119    ) -> Self
 120    where
 121        Self: Sized,
 122    {
 123        self.interactivity().mouse_up_listeners.push(Box::new(
 124            move |view, event, bounds, phase, cx| {
 125                if phase == DispatchPhase::Capture
 126                    && event.button == button
 127                    && !bounds.contains_point(&event.position)
 128                {
 129                    handler(view, event, cx);
 130                }
 131            },
 132        ));
 133        self
 134    }
 135
 136    fn on_mouse_move(
 137        mut self,
 138        handler: impl Fn(&mut V, &MouseMoveEvent, &mut ViewContext<V>) + 'static,
 139    ) -> Self
 140    where
 141        Self: Sized,
 142    {
 143        self.interactivity().mouse_move_listeners.push(Box::new(
 144            move |view, event, bounds, phase, cx| {
 145                if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 146                    handler(view, event, cx);
 147                }
 148            },
 149        ));
 150        self
 151    }
 152
 153    fn on_scroll_wheel(
 154        mut self,
 155        handler: impl Fn(&mut V, &ScrollWheelEvent, &mut ViewContext<V>) + 'static,
 156    ) -> Self
 157    where
 158        Self: Sized,
 159    {
 160        self.interactivity().scroll_wheel_listeners.push(Box::new(
 161            move |view, event, bounds, phase, cx| {
 162                if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 163                    handler(view, event, cx);
 164                }
 165            },
 166        ));
 167        self
 168    }
 169
 170    /// Capture the given action, fires during the capture phase
 171    fn capture_action<A: Action>(
 172        mut self,
 173        listener: impl Fn(&mut V, &A, &mut ViewContext<V>) + 'static,
 174    ) -> Self
 175    where
 176        Self: Sized,
 177    {
 178        self.interactivity().action_listeners.push((
 179            TypeId::of::<A>(),
 180            Box::new(move |view, action, phase, cx| {
 181                let action = action.downcast_ref().unwrap();
 182                if phase == DispatchPhase::Capture {
 183                    listener(view, action, cx)
 184                }
 185            }),
 186        ));
 187        self
 188    }
 189
 190    /// Add a listener for the given action, fires during the bubble event phase
 191    fn on_action<A: Action>(
 192        mut self,
 193        listener: impl Fn(&mut V, &A, &mut ViewContext<V>) + 'static,
 194    ) -> Self
 195    where
 196        Self: Sized,
 197    {
 198        self.interactivity().action_listeners.push((
 199            TypeId::of::<A>(),
 200            Box::new(move |view, action, phase, cx| {
 201                let action = action.downcast_ref().unwrap();
 202                if phase == DispatchPhase::Bubble {
 203                    listener(view, action, cx)
 204                }
 205            }),
 206        ));
 207        self
 208    }
 209
 210    fn on_key_down(
 211        mut self,
 212        listener: impl Fn(&mut V, &KeyDownEvent, DispatchPhase, &mut ViewContext<V>) + 'static,
 213    ) -> Self
 214    where
 215        Self: Sized,
 216    {
 217        self.interactivity()
 218            .key_down_listeners
 219            .push(Box::new(move |view, event, phase, cx| {
 220                listener(view, event, phase, cx)
 221            }));
 222        self
 223    }
 224
 225    fn on_key_up(
 226        mut self,
 227        listener: impl Fn(&mut V, &KeyUpEvent, DispatchPhase, &mut ViewContext<V>) + 'static,
 228    ) -> Self
 229    where
 230        Self: Sized,
 231    {
 232        self.interactivity()
 233            .key_up_listeners
 234            .push(Box::new(move |view, event, phase, cx| {
 235                listener(view, event, phase, cx)
 236            }));
 237        self
 238    }
 239
 240    fn drag_over<S: 'static>(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
 241    where
 242        Self: Sized,
 243    {
 244        self.interactivity()
 245            .drag_over_styles
 246            .push((TypeId::of::<S>(), f(StyleRefinement::default())));
 247        self
 248    }
 249
 250    fn group_drag_over<S: 'static>(
 251        mut self,
 252        group_name: impl Into<SharedString>,
 253        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
 254    ) -> Self
 255    where
 256        Self: Sized,
 257    {
 258        self.interactivity().group_drag_over_styles.push((
 259            TypeId::of::<S>(),
 260            GroupStyle {
 261                group: group_name.into(),
 262                style: f(StyleRefinement::default()),
 263            },
 264        ));
 265        self
 266    }
 267
 268    fn on_drop<W: 'static>(
 269        mut self,
 270        listener: impl Fn(&mut V, View<W>, &mut ViewContext<V>) + 'static,
 271    ) -> Self
 272    where
 273        Self: Sized,
 274    {
 275        self.interactivity().drop_listeners.push((
 276            TypeId::of::<W>(),
 277            Box::new(move |view, dragged_view, cx| {
 278                listener(view, dragged_view.downcast().unwrap(), cx);
 279            }),
 280        ));
 281        self
 282    }
 283}
 284
 285pub trait StatefulInteractiveComponent<V: 'static, E: Element<V>>: InteractiveComponent<V> {
 286    fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
 287    where
 288        Self: Sized,
 289    {
 290        self.interactivity().active_style = f(StyleRefinement::default());
 291        self
 292    }
 293
 294    fn group_active(
 295        mut self,
 296        group_name: impl Into<SharedString>,
 297        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
 298    ) -> Self
 299    where
 300        Self: Sized,
 301    {
 302        self.interactivity().group_active_style = Some(GroupStyle {
 303            group: group_name.into(),
 304            style: f(StyleRefinement::default()),
 305        });
 306        self
 307    }
 308
 309    fn on_click(
 310        mut self,
 311        listener: impl Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + 'static,
 312    ) -> Self
 313    where
 314        Self: Sized,
 315    {
 316        self.interactivity()
 317            .click_listeners
 318            .push(Box::new(move |view, event, cx| listener(view, event, cx)));
 319        self
 320    }
 321
 322    fn on_drag<W>(
 323        mut self,
 324        listener: impl Fn(&mut V, &mut ViewContext<V>) -> View<W> + 'static,
 325    ) -> Self
 326    where
 327        Self: Sized,
 328        W: 'static + Render,
 329    {
 330        debug_assert!(
 331            self.interactivity().drag_listener.is_none(),
 332            "calling on_drag more than once on the same element is not supported"
 333        );
 334        self.interactivity().drag_listener =
 335            Some(Box::new(move |view_state, cursor_offset, cx| AnyDrag {
 336                view: listener(view_state, cx).into(),
 337                cursor_offset,
 338            }));
 339        self
 340    }
 341
 342    fn on_hover(mut self, listener: impl 'static + Fn(&mut V, bool, &mut ViewContext<V>)) -> Self
 343    where
 344        Self: Sized,
 345    {
 346        debug_assert!(
 347            self.interactivity().hover_listener.is_none(),
 348            "calling on_hover more than once on the same element is not supported"
 349        );
 350        self.interactivity().hover_listener = Some(Box::new(listener));
 351        self
 352    }
 353
 354    fn tooltip<W>(
 355        mut self,
 356        build_tooltip: impl Fn(&mut V, &mut ViewContext<V>) -> View<W> + 'static,
 357    ) -> Self
 358    where
 359        Self: Sized,
 360        W: 'static + Render,
 361    {
 362        debug_assert!(
 363            self.interactivity().tooltip_builder.is_none(),
 364            "calling tooltip more than once on the same element is not supported"
 365        );
 366        self.interactivity().tooltip_builder = Some(Arc::new(move |view_state, cx| {
 367            build_tooltip(view_state, cx).into()
 368        }));
 369
 370        self
 371    }
 372}
 373
 374pub trait FocusableComponent<V> {
 375    fn focusability(&mut self) -> &mut Focusability<V>;
 376
 377    fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
 378    where
 379        Self: Sized,
 380    {
 381        self.focusability().focus_style = f(StyleRefinement::default());
 382        self
 383    }
 384
 385    fn focus_in(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
 386    where
 387        Self: Sized,
 388    {
 389        self.focusability().focus_in_style = f(StyleRefinement::default());
 390        self
 391    }
 392
 393    fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
 394    where
 395        Self: Sized,
 396    {
 397        self.focusability().in_focus_style = f(StyleRefinement::default());
 398        self
 399    }
 400
 401    fn on_focus(
 402        mut self,
 403        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
 404    ) -> Self
 405    where
 406        Self: Sized,
 407    {
 408        self.focusability()
 409            .focus_listeners
 410            .push(Box::new(move |view, focus_handle, event, cx| {
 411                if event.focused.as_ref() == Some(focus_handle) {
 412                    listener(view, event, cx)
 413                }
 414            }));
 415        self
 416    }
 417
 418    fn on_blur(
 419        mut self,
 420        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
 421    ) -> Self
 422    where
 423        Self: Sized,
 424    {
 425        self.focusability()
 426            .focus_listeners
 427            .push(Box::new(move |view, focus_handle, event, cx| {
 428                if event.blurred.as_ref() == Some(focus_handle) {
 429                    listener(view, event, cx)
 430                }
 431            }));
 432        self
 433    }
 434
 435    fn on_focus_in(
 436        mut self,
 437        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
 438    ) -> Self
 439    where
 440        Self: Sized,
 441    {
 442        self.focusability()
 443            .focus_listeners
 444            .push(Box::new(move |view, focus_handle, event, cx| {
 445                let descendant_blurred = event
 446                    .blurred
 447                    .as_ref()
 448                    .map_or(false, |blurred| focus_handle.contains(blurred, cx));
 449                let descendant_focused = event
 450                    .focused
 451                    .as_ref()
 452                    .map_or(false, |focused| focus_handle.contains(focused, cx));
 453
 454                if !descendant_blurred && descendant_focused {
 455                    listener(view, event, cx)
 456                }
 457            }));
 458        self
 459    }
 460
 461    fn on_focus_out(
 462        mut self,
 463        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
 464    ) -> Self
 465    where
 466        Self: Sized,
 467    {
 468        self.focusability()
 469            .focus_listeners
 470            .push(Box::new(move |view, focus_handle, event, cx| {
 471                let descendant_blurred = event
 472                    .blurred
 473                    .as_ref()
 474                    .map_or(false, |blurred| focus_handle.contains(blurred, cx));
 475                let descendant_focused = event
 476                    .focused
 477                    .as_ref()
 478                    .map_or(false, |focused| focus_handle.contains(focused, cx));
 479                if descendant_blurred && !descendant_focused {
 480                    listener(view, event, cx)
 481                }
 482            }));
 483        self
 484    }
 485}
 486
 487pub type FocusListeners<V> = SmallVec<[FocusListener<V>; 2]>;
 488
 489pub type FocusListener<V> =
 490    Box<dyn Fn(&mut V, &FocusHandle, &FocusEvent, &mut ViewContext<V>) + 'static>;
 491
 492pub type MouseDownListener<V> = Box<
 493    dyn Fn(&mut V, &MouseDownEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
 494>;
 495pub type MouseUpListener<V> = Box<
 496    dyn Fn(&mut V, &MouseUpEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
 497>;
 498
 499pub type MouseMoveListener<V> = Box<
 500    dyn Fn(&mut V, &MouseMoveEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
 501>;
 502
 503pub type ScrollWheelListener<V> = Box<
 504    dyn Fn(&mut V, &ScrollWheelEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
 505        + 'static,
 506>;
 507
 508pub type ClickListener<V> = Box<dyn Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + 'static>;
 509
 510pub type DragListener<V> =
 511    Box<dyn Fn(&mut V, Point<Pixels>, &mut ViewContext<V>) -> AnyDrag + 'static>;
 512
 513type DropListener<V> = dyn Fn(&mut V, AnyView, &mut ViewContext<V>) + 'static;
 514
 515pub type HoverListener<V> = Box<dyn Fn(&mut V, bool, &mut ViewContext<V>) + 'static>;
 516
 517pub type TooltipBuilder<V> = Arc<dyn Fn(&mut V, &mut ViewContext<V>) -> AnyView + 'static>;
 518
 519pub type KeyDownListener<V> =
 520    Box<dyn Fn(&mut V, &KeyDownEvent, DispatchPhase, &mut ViewContext<V>) + 'static>;
 521
 522pub type KeyUpListener<V> =
 523    Box<dyn Fn(&mut V, &KeyUpEvent, DispatchPhase, &mut ViewContext<V>) + 'static>;
 524
 525pub type ActionListener<V> =
 526    Box<dyn Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static>;
 527
 528pub struct FocusEvent {
 529    pub blurred: Option<FocusHandle>,
 530    pub focused: Option<FocusHandle>,
 531}
 532
 533pub struct Node<V> {
 534    interactivity: Interactivity<V>,
 535    children: Vec<AnyElement<V>>,
 536}
 537
 538impl<V> Styled for Node<V> {
 539    fn style(&mut self) -> &mut StyleRefinement {
 540        &mut self.interactivity.base_style
 541    }
 542}
 543
 544impl<V: 'static> InteractiveComponent<V> for Node<V> {
 545    fn interactivity(&mut self) -> &mut Interactivity<V> {
 546        &mut self.interactivity
 547    }
 548}
 549
 550impl<V: 'static> Element<V> for Node<V> {
 551    type ElementState = NodeState;
 552
 553    fn id(&self) -> Option<ElementId> {
 554        self.interactivity.element_id.clone()
 555    }
 556
 557    fn initialize(
 558        &mut self,
 559        view_state: &mut V,
 560        element_state: Option<Self::ElementState>,
 561        cx: &mut ViewContext<V>,
 562    ) -> Self::ElementState {
 563        let interactive_state = self
 564            .interactivity
 565            .initialize(element_state.map(|s| s.interactive_state), cx);
 566        for child in &mut self.children {
 567            child.initialize(view_state, cx);
 568        }
 569
 570        NodeState {
 571            interactive_state,
 572            child_layout_ids: SmallVec::new(),
 573        }
 574    }
 575
 576    fn layout(
 577        &mut self,
 578        view_state: &mut V,
 579        element_state: &mut Self::ElementState,
 580        cx: &mut ViewContext<V>,
 581    ) -> crate::LayoutId {
 582        let mut interactivity = mem::take(&mut self.interactivity);
 583        let layout_id =
 584            interactivity.layout(&mut element_state.interactive_state, cx, |style, cx| {
 585                cx.with_text_style(style.text_style().cloned(), |cx| {
 586                    element_state.child_layout_ids = self
 587                        .children
 588                        .iter_mut()
 589                        .map(|child| child.layout(view_state, cx))
 590                        .collect::<SmallVec<_>>();
 591                    cx.request_layout(&style, element_state.child_layout_ids.iter().copied())
 592                })
 593            });
 594        self.interactivity = interactivity;
 595        layout_id
 596    }
 597
 598    fn paint(
 599        &mut self,
 600        bounds: Bounds<Pixels>,
 601        view_state: &mut V,
 602        element_state: &mut Self::ElementState,
 603        cx: &mut ViewContext<V>,
 604    ) {
 605        let mut child_min = point(Pixels::MAX, Pixels::MAX);
 606        let mut child_max = Point::default();
 607        let content_size = if element_state.child_layout_ids.is_empty() {
 608            bounds.size
 609        } else {
 610            for child_layout_id in &element_state.child_layout_ids {
 611                let child_bounds = cx.layout_bounds(*child_layout_id);
 612                child_min = child_min.min(&child_bounds.origin);
 613                child_max = child_max.max(&child_bounds.lower_right());
 614            }
 615            (child_max - child_min).into()
 616        };
 617
 618        let mut interactivity = mem::take(&mut self.interactivity);
 619        interactivity.paint(
 620            bounds,
 621            content_size,
 622            &mut element_state.interactive_state,
 623            cx,
 624            |style, scroll_offset, cx| {
 625                if style.visibility == Visibility::Hidden {
 626                    return;
 627                }
 628
 629                let z_index = style.z_index.unwrap_or(0);
 630
 631                cx.with_z_index(z_index, |cx| {
 632                    cx.with_z_index(0, |cx| {
 633                        style.paint(bounds, cx);
 634                    });
 635                    cx.with_z_index(1, |cx| {
 636                        cx.with_text_style(style.text_style().cloned(), |cx| {
 637                            cx.with_content_mask(style.overflow_mask(bounds), |cx| {
 638                                cx.with_element_offset(scroll_offset, |cx| {
 639                                    for child in &mut self.children {
 640                                        child.paint(view_state, cx);
 641                                    }
 642                                })
 643                            })
 644                        })
 645                    })
 646                })
 647            },
 648        );
 649        self.interactivity = interactivity;
 650    }
 651}
 652
 653pub struct NodeState {
 654    child_layout_ids: SmallVec<[LayoutId; 4]>,
 655    interactive_state: InteractiveElementState,
 656}
 657
 658pub struct Interactivity<V> {
 659    element_id: Option<ElementId>,
 660    key_context: KeyContext,
 661    tracked_focus_handle: Option<FocusHandle>,
 662    focusable: bool,
 663    scroll_offset: Point<Pixels>,
 664    group: Option<SharedString>,
 665    base_style: StyleRefinement,
 666    focus_style: StyleRefinement,
 667    focus_in_style: StyleRefinement,
 668    in_focus_style: StyleRefinement,
 669    hover_style: StyleRefinement,
 670    group_hover_style: Option<GroupStyle>,
 671    active_style: StyleRefinement,
 672    group_active_style: Option<GroupStyle>,
 673    drag_over_styles: SmallVec<[(TypeId, StyleRefinement); 2]>,
 674    group_drag_over_styles: SmallVec<[(TypeId, GroupStyle); 2]>,
 675    mouse_down_listeners: SmallVec<[MouseDownListener<V>; 2]>,
 676    mouse_up_listeners: SmallVec<[MouseUpListener<V>; 2]>,
 677    mouse_move_listeners: SmallVec<[MouseMoveListener<V>; 2]>,
 678    scroll_wheel_listeners: SmallVec<[ScrollWheelListener<V>; 2]>,
 679    key_down_listeners: SmallVec<[KeyDownListener<V>; 2]>,
 680    key_up_listeners: SmallVec<[KeyUpListener<V>; 2]>,
 681    action_listeners: SmallVec<[(TypeId, ActionListener<V>); 8]>,
 682    drop_listeners: SmallVec<[(TypeId, Box<DropListener<V>>); 2]>,
 683    click_listeners: SmallVec<[ClickListener<V>; 2]>,
 684    drag_listener: Option<DragListener<V>>,
 685    hover_listener: Option<HoverListener<V>>,
 686    tooltip_builder: Option<TooltipBuilder<V>>,
 687}
 688
 689impl<V> Interactivity<V>
 690where
 691    V: 'static,
 692{
 693    fn initialize(
 694        &mut self,
 695        element_state: Option<InteractiveElementState>,
 696        cx: &mut ViewContext<V>,
 697    ) -> InteractiveElementState {
 698        let mut element_state = element_state.unwrap_or_default();
 699
 700        // Ensure we store a focus handle in our element state if we're focusable.
 701        // If there's an explicit focus handle we're tracking, use that. Otherwise
 702        // create a new handle and store it in the element state, which lives for as
 703        // as frames contain an element with this id.
 704        if self.focusable {
 705            element_state.focus_handle.get_or_insert_with(|| {
 706                self.tracked_focus_handle
 707                    .clone()
 708                    .unwrap_or_else(|| cx.focus_handle())
 709            });
 710        }
 711        element_state
 712    }
 713
 714    fn layout(
 715        &mut self,
 716        element_state: &mut InteractiveElementState,
 717        cx: &mut ViewContext<V>,
 718        f: impl FnOnce(Style, &mut ViewContext<V>) -> LayoutId,
 719    ) -> LayoutId {
 720        let style = self.compute_style(None, element_state, cx);
 721        cx.with_element_id(self.element_id.clone(), |cx| {
 722            cx.with_key_dispatch(
 723                self.key_context.clone(),
 724                self.tracked_focus_handle.clone(),
 725                |_, cx| f(style, cx),
 726            )
 727        })
 728    }
 729
 730    fn paint(
 731        &mut self,
 732        bounds: Bounds<Pixels>,
 733        content_size: Size<Pixels>,
 734        element_state: &mut InteractiveElementState,
 735        cx: &mut ViewContext<V>,
 736        f: impl FnOnce(Style, Point<Pixels>, &mut ViewContext<V>),
 737    ) {
 738        let style = self.compute_style(Some(bounds), element_state, cx);
 739
 740        if let Some(mouse_cursor) = style.mouse_cursor {
 741            let hovered = bounds.contains_point(&cx.mouse_position());
 742            if hovered {
 743                cx.set_cursor_style(mouse_cursor);
 744            }
 745        }
 746
 747        for listener in self.mouse_down_listeners.drain(..) {
 748            cx.on_mouse_event(move |state, event: &MouseDownEvent, phase, cx| {
 749                listener(state, event, &bounds, phase, cx);
 750            })
 751        }
 752
 753        for listener in self.mouse_up_listeners.drain(..) {
 754            cx.on_mouse_event(move |state, event: &MouseUpEvent, phase, cx| {
 755                listener(state, event, &bounds, phase, cx);
 756            })
 757        }
 758
 759        for listener in self.mouse_move_listeners.drain(..) {
 760            cx.on_mouse_event(move |state, event: &MouseMoveEvent, phase, cx| {
 761                listener(state, event, &bounds, phase, cx);
 762            })
 763        }
 764
 765        for listener in self.scroll_wheel_listeners.drain(..) {
 766            cx.on_mouse_event(move |state, event: &ScrollWheelEvent, phase, cx| {
 767                listener(state, event, &bounds, phase, cx);
 768            })
 769        }
 770
 771        let hover_group_bounds = self
 772            .group_hover_style
 773            .as_ref()
 774            .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
 775
 776        if let Some(group_bounds) = hover_group_bounds {
 777            let hovered = group_bounds.contains_point(&cx.mouse_position());
 778            cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
 779                if phase == DispatchPhase::Capture {
 780                    if group_bounds.contains_point(&event.position) != hovered {
 781                        cx.notify();
 782                    }
 783                }
 784            });
 785        }
 786
 787        if self.hover_style.is_some()
 788            || (cx.active_drag.is_some() && !self.drag_over_styles.is_empty())
 789        {
 790            let hovered = bounds.contains_point(&cx.mouse_position());
 791            cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
 792                if phase == DispatchPhase::Capture {
 793                    if bounds.contains_point(&event.position) != hovered {
 794                        cx.notify();
 795                    }
 796                }
 797            });
 798        }
 799
 800        if cx.active_drag.is_some() {
 801            let drop_listeners = mem::take(&mut self.drop_listeners);
 802            cx.on_mouse_event(move |view, event: &MouseUpEvent, phase, cx| {
 803                if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 804                    if let Some(drag_state_type) =
 805                        cx.active_drag.as_ref().map(|drag| drag.view.entity_type())
 806                    {
 807                        for (drop_state_type, listener) in &drop_listeners {
 808                            if *drop_state_type == drag_state_type {
 809                                let drag = cx
 810                                    .active_drag
 811                                    .take()
 812                                    .expect("checked for type drag state type above");
 813                                listener(view, drag.view.clone(), cx);
 814                                cx.notify();
 815                                cx.stop_propagation();
 816                            }
 817                        }
 818                    }
 819                }
 820            });
 821        }
 822
 823        let click_listeners = mem::take(&mut self.click_listeners);
 824        let drag_listener = mem::take(&mut self.drag_listener);
 825
 826        if !click_listeners.is_empty() || drag_listener.is_some() {
 827            let pending_mouse_down = element_state.pending_mouse_down.clone();
 828            let mouse_down = pending_mouse_down.lock().clone();
 829            if let Some(mouse_down) = mouse_down {
 830                if let Some(drag_listener) = drag_listener {
 831                    let active_state = element_state.clicked_state.clone();
 832
 833                    cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
 834                        if cx.active_drag.is_some() {
 835                            if phase == DispatchPhase::Capture {
 836                                cx.notify();
 837                            }
 838                        } else if phase == DispatchPhase::Bubble
 839                            && bounds.contains_point(&event.position)
 840                            && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
 841                        {
 842                            *active_state.lock() = ElementClickedState::default();
 843                            let cursor_offset = event.position - bounds.origin;
 844                            let drag = drag_listener(view_state, cursor_offset, cx);
 845                            cx.active_drag = Some(drag);
 846                            cx.notify();
 847                            cx.stop_propagation();
 848                        }
 849                    });
 850                }
 851
 852                cx.on_mouse_event(move |view_state, event: &MouseUpEvent, phase, cx| {
 853                    if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 854                        let mouse_click = ClickEvent {
 855                            down: mouse_down.clone(),
 856                            up: event.clone(),
 857                        };
 858                        for listener in &click_listeners {
 859                            listener(view_state, &mouse_click, cx);
 860                        }
 861                    }
 862                    *pending_mouse_down.lock() = None;
 863                });
 864            } else {
 865                cx.on_mouse_event(move |_state, event: &MouseDownEvent, phase, _cx| {
 866                    if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 867                        *pending_mouse_down.lock() = Some(event.clone());
 868                    }
 869                });
 870            }
 871        }
 872
 873        if let Some(hover_listener) = self.hover_listener.take() {
 874            let was_hovered = element_state.hover_state.clone();
 875            let has_mouse_down = element_state.pending_mouse_down.clone();
 876
 877            cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
 878                if phase != DispatchPhase::Bubble {
 879                    return;
 880                }
 881                let is_hovered =
 882                    bounds.contains_point(&event.position) && has_mouse_down.lock().is_none();
 883                let mut was_hovered = was_hovered.lock();
 884
 885                if is_hovered != was_hovered.clone() {
 886                    *was_hovered = is_hovered;
 887                    drop(was_hovered);
 888
 889                    hover_listener(view_state, is_hovered, cx);
 890                }
 891            });
 892        }
 893
 894        if let Some(tooltip_builder) = self.tooltip_builder.take() {
 895            let active_tooltip = element_state.active_tooltip.clone();
 896            let pending_mouse_down = element_state.pending_mouse_down.clone();
 897
 898            cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
 899                if phase != DispatchPhase::Bubble {
 900                    return;
 901                }
 902
 903                let is_hovered =
 904                    bounds.contains_point(&event.position) && pending_mouse_down.lock().is_none();
 905                if !is_hovered {
 906                    active_tooltip.lock().take();
 907                    return;
 908                }
 909
 910                if active_tooltip.lock().is_none() {
 911                    let task = cx.spawn({
 912                        let active_tooltip = active_tooltip.clone();
 913                        let tooltip_builder = tooltip_builder.clone();
 914
 915                        move |view, mut cx| async move {
 916                            cx.background_executor().timer(TOOLTIP_DELAY).await;
 917                            view.update(&mut cx, move |view_state, cx| {
 918                                active_tooltip.lock().replace(ActiveTooltip {
 919                                    waiting: None,
 920                                    tooltip: Some(AnyTooltip {
 921                                        view: tooltip_builder(view_state, cx),
 922                                        cursor_offset: cx.mouse_position() + TOOLTIP_OFFSET,
 923                                    }),
 924                                });
 925                                cx.notify();
 926                            })
 927                            .ok();
 928                        }
 929                    });
 930                    active_tooltip.lock().replace(ActiveTooltip {
 931                        waiting: Some(task),
 932                        tooltip: None,
 933                    });
 934                }
 935            });
 936
 937            if let Some(active_tooltip) = element_state.active_tooltip.lock().as_ref() {
 938                if active_tooltip.tooltip.is_some() {
 939                    cx.active_tooltip = active_tooltip.tooltip.clone()
 940                }
 941            }
 942        }
 943
 944        let active_state = element_state.clicked_state.clone();
 945        if !active_state.lock().is_clicked() {
 946            cx.on_mouse_event(move |_, _: &MouseUpEvent, phase, cx| {
 947                if phase == DispatchPhase::Capture {
 948                    *active_state.lock() = ElementClickedState::default();
 949                    cx.notify();
 950                }
 951            });
 952        } else {
 953            let active_group_bounds = self
 954                .group_active_style
 955                .as_ref()
 956                .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
 957            cx.on_mouse_event(move |_view, down: &MouseDownEvent, phase, cx| {
 958                if phase == DispatchPhase::Bubble {
 959                    let group = active_group_bounds
 960                        .map_or(false, |bounds| bounds.contains_point(&down.position));
 961                    let element = bounds.contains_point(&down.position);
 962                    if group || element {
 963                        *active_state.lock() = ElementClickedState { group, element };
 964                        cx.notify();
 965                    }
 966                }
 967            });
 968        }
 969
 970        let overflow = style.overflow;
 971        if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
 972            let scroll_offset = element_state
 973                .scroll_offset
 974                .get_or_insert_with(Arc::default)
 975                .clone();
 976            let line_height = cx.line_height();
 977            let scroll_max = (content_size - bounds.size).max(&Size::default());
 978
 979            cx.on_mouse_event(move |_, event: &ScrollWheelEvent, phase, cx| {
 980                if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 981                    let mut scroll_offset = scroll_offset.lock();
 982                    let old_scroll_offset = *scroll_offset;
 983                    let delta = event.delta.pixel_delta(line_height);
 984
 985                    if overflow.x == Overflow::Scroll {
 986                        scroll_offset.x =
 987                            (scroll_offset.x + delta.x).clamp(-scroll_max.width, px(0.));
 988                    }
 989
 990                    if overflow.y == Overflow::Scroll {
 991                        scroll_offset.y =
 992                            (scroll_offset.y + delta.y).clamp(-scroll_max.height, px(0.));
 993                    }
 994
 995                    if *scroll_offset != old_scroll_offset {
 996                        cx.notify();
 997                        cx.stop_propagation();
 998                    }
 999                }
1000            });
1001        }
1002
1003        if let Some(group) = self.group.clone() {
1004            GroupBounds::push(group, bounds, cx);
1005        }
1006
1007        cx.with_element_id(self.element_id.clone(), |cx| {
1008            cx.with_key_dispatch(
1009                self.key_context.clone(),
1010                self.tracked_focus_handle.clone(),
1011                |_, cx| {
1012                    for listener in self.key_down_listeners.drain(..) {
1013                        cx.on_key_event(move |state, event: &KeyDownEvent, phase, cx| {
1014                            listener(state, event, phase, cx);
1015                        })
1016                    }
1017
1018                    for listener in self.key_up_listeners.drain(..) {
1019                        cx.on_key_event(move |state, event: &KeyUpEvent, phase, cx| {
1020                            listener(state, event, phase, cx);
1021                        })
1022                    }
1023
1024                    for (action_type, listener) in self.action_listeners.drain(..) {
1025                        cx.on_action(action_type, listener)
1026                    }
1027
1028                    f(style, self.scroll_offset, cx)
1029                },
1030            );
1031        });
1032
1033        if let Some(group) = self.group.as_ref() {
1034            GroupBounds::pop(group, cx);
1035        }
1036    }
1037
1038    fn compute_style(
1039        &self,
1040        bounds: Option<Bounds<Pixels>>,
1041        element_state: &mut InteractiveElementState,
1042        cx: &mut ViewContext<V>,
1043    ) -> Style {
1044        let mut style = Style::default();
1045        style.refine(&self.base_style);
1046
1047        if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
1048            if focus_handle.contains_focused(cx) {
1049                style.refine(&self.focus_in_style);
1050            }
1051
1052            if focus_handle.within_focused(cx) {
1053                style.refine(&self.in_focus_style);
1054            }
1055
1056            if focus_handle.is_focused(cx) {
1057                style.refine(&self.focus_style);
1058            }
1059        }
1060
1061        if let Some(bounds) = bounds {
1062            let mouse_position = cx.mouse_position();
1063            if let Some(group_hover) = self.group_hover_style.as_ref() {
1064                if let Some(group_bounds) = GroupBounds::get(&group_hover.group, cx) {
1065                    if group_bounds.contains_point(&mouse_position) {
1066                        style.refine(&group_hover.style);
1067                    }
1068                }
1069            }
1070            if bounds.contains_point(&mouse_position) {
1071                style.refine(&self.hover_style);
1072            }
1073
1074            if let Some(drag) = cx.active_drag.take() {
1075                for (state_type, group_drag_style) in &self.group_drag_over_styles {
1076                    if let Some(group_bounds) = GroupBounds::get(&group_drag_style.group, cx) {
1077                        if *state_type == drag.view.entity_type()
1078                            && group_bounds.contains_point(&mouse_position)
1079                        {
1080                            style.refine(&group_drag_style.style);
1081                        }
1082                    }
1083                }
1084
1085                for (state_type, drag_over_style) in &self.drag_over_styles {
1086                    if *state_type == drag.view.entity_type()
1087                        && bounds.contains_point(&mouse_position)
1088                    {
1089                        style.refine(drag_over_style);
1090                    }
1091                }
1092
1093                cx.active_drag = Some(drag);
1094            }
1095        }
1096
1097        let clicked_state = element_state.clicked_state.lock();
1098        if clicked_state.group {
1099            if let Some(group) = self.group_active_style.as_ref() {
1100                style.refine(&group.style)
1101            }
1102        }
1103
1104        if clicked_state.element {
1105            style.refine(&self.active_style)
1106        }
1107
1108        style
1109    }
1110}
1111
1112impl<V: 'static> Default for Interactivity<V> {
1113    fn default() -> Self {
1114        Self {
1115            element_id: None,
1116            key_context: KeyContext::default(),
1117            tracked_focus_handle: None,
1118            scroll_offset: Point::default(),
1119            group: None,
1120            base_style: StyleRefinement::default(),
1121            focus_style: StyleRefinement::default(),
1122            focus_in_style: StyleRefinement::default(),
1123            in_focus_style: StyleRefinement::default(),
1124            hover_style: StyleRefinement::default(),
1125            group_hover_style: None,
1126            active_style: StyleRefinement::default(),
1127            group_active_style: None,
1128            drag_over_styles: SmallVec::new(),
1129            group_drag_over_styles: SmallVec::new(),
1130            mouse_down_listeners: SmallVec::new(),
1131            mouse_up_listeners: SmallVec::new(),
1132            mouse_move_listeners: SmallVec::new(),
1133            scroll_wheel_listeners: SmallVec::new(),
1134            key_down_listeners: SmallVec::new(),
1135            key_up_listeners: SmallVec::new(),
1136            action_listeners: SmallVec::new(),
1137            drop_listeners: SmallVec::new(),
1138            click_listeners: SmallVec::new(),
1139            drag_listener: None,
1140            hover_listener: None,
1141            tooltip_builder: None,
1142            focusable: false,
1143        }
1144    }
1145}
1146
1147#[derive(Default)]
1148pub struct InteractiveElementState {
1149    focus_handle: Option<FocusHandle>,
1150    clicked_state: Arc<Mutex<ElementClickedState>>,
1151    hover_state: Arc<Mutex<bool>>,
1152    pending_mouse_down: Arc<Mutex<Option<MouseDownEvent>>>,
1153    scroll_offset: Option<Arc<Mutex<Point<Pixels>>>>,
1154    active_tooltip: Arc<Mutex<Option<ActiveTooltip>>>,
1155}
1156
1157struct ActiveTooltip {
1158    #[allow(unused)] // used to drop the task
1159    waiting: Option<Task<()>>,
1160    tooltip: Option<AnyTooltip>,
1161}
1162
1163/// Whether or not the element or a group that contains it is clicked by the mouse.
1164#[derive(Copy, Clone, Default, Eq, PartialEq)]
1165struct ElementClickedState {
1166    pub group: bool,
1167    pub element: bool,
1168}
1169
1170impl ElementClickedState {
1171    fn is_clicked(&self) -> bool {
1172        self.group || self.element
1173    }
1174}
1175
1176#[derive(Default)]
1177pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
1178
1179impl GroupBounds {
1180    pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
1181        cx.default_global::<Self>()
1182            .0
1183            .get(name)
1184            .and_then(|bounds_stack| bounds_stack.last())
1185            .cloned()
1186    }
1187
1188    pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
1189        cx.default_global::<Self>()
1190            .0
1191            .entry(name)
1192            .or_default()
1193            .push(bounds);
1194    }
1195
1196    pub fn pop(name: &SharedString, cx: &mut AppContext) {
1197        cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
1198    }
1199}
1200
1201pub struct Focusable<V, E> {
1202    focusability: Focusability<V>,
1203    view_type: PhantomData<V>,
1204    element: E,
1205}
1206
1207pub struct Focusability<V> {
1208    focus_handle: Option<FocusHandle>,
1209    focus_listeners: FocusListeners<V>,
1210    focus_style: StyleRefinement,
1211    focus_in_style: StyleRefinement,
1212    in_focus_style: StyleRefinement,
1213}
1214
1215impl<V, E> FocusableComponent<V> for Focusable<V, E> {
1216    fn focusability(&mut self) -> &mut Focusability<V> {
1217        &mut self.focusability
1218    }
1219}
1220
1221impl<V, E> InteractiveComponent<V> for Focusable<V, E>
1222where
1223    V: 'static,
1224    E: InteractiveComponent<V>,
1225{
1226    fn interactivity(&mut self) -> &mut Interactivity<V> {
1227        self.element.interactivity()
1228    }
1229}
1230
1231impl<V: 'static, E: StatefulInteractiveComponent<V, E>> StatefulInteractiveComponent<V, E>
1232    for Focusable<V, E>
1233{
1234}
1235
1236impl<V, E> Element<V> for Focusable<V, E>
1237where
1238    V: 'static,
1239    E: Element<V>,
1240{
1241    type ElementState = E::ElementState;
1242
1243    fn id(&self) -> Option<ElementId> {
1244        self.element.id()
1245    }
1246
1247    fn initialize(
1248        &mut self,
1249        view_state: &mut V,
1250        element_state: Option<Self::ElementState>,
1251        cx: &mut ViewContext<V>,
1252    ) -> Self::ElementState {
1253        self.element.initialize(view_state, element_state, cx)
1254    }
1255
1256    fn layout(
1257        &mut self,
1258        view_state: &mut V,
1259        element_state: &mut Self::ElementState,
1260        cx: &mut ViewContext<V>,
1261    ) -> LayoutId {
1262        self.element.layout(view_state, element_state, cx)
1263    }
1264
1265    fn paint(
1266        &mut self,
1267        bounds: Bounds<Pixels>,
1268        view_state: &mut V,
1269        element_state: &mut Self::ElementState,
1270        cx: &mut ViewContext<V>,
1271    ) {
1272        self.element.paint(bounds, view_state, element_state, cx);
1273    }
1274}
1275
1276pub struct Stateful<V, E> {
1277    id: SharedString,
1278    view_type: PhantomData<V>,
1279    element: E,
1280}
1281
1282impl<V, E> StatefulInteractiveComponent<V, E> for Stateful<V, E>
1283where
1284    V: 'static,
1285    E: Element<V>,
1286    Self: InteractiveComponent<V>,
1287{
1288}
1289
1290impl<V, E> InteractiveComponent<V> for Stateful<V, E>
1291where
1292    V: 'static,
1293    E: InteractiveComponent<V>,
1294{
1295    fn interactivity(&mut self) -> &mut Interactivity<V> {
1296        self.element.interactivity()
1297    }
1298}
1299
1300impl<V, E: FocusableComponent<V>> FocusableComponent<V> for Stateful<V, E> {
1301    fn focusability(&mut self) -> &mut Focusability<V> {
1302        self.element.focusability()
1303    }
1304}
1305
1306impl<V, E> Element<V> for Stateful<V, E>
1307where
1308    V: 'static,
1309    E: Element<V>,
1310{
1311    type ElementState = E::ElementState;
1312
1313    fn id(&self) -> Option<ElementId> {
1314        self.element.id()
1315    }
1316
1317    fn initialize(
1318        &mut self,
1319        view_state: &mut V,
1320        element_state: Option<Self::ElementState>,
1321        cx: &mut ViewContext<V>,
1322    ) -> Self::ElementState {
1323        self.element.initialize(view_state, element_state, cx)
1324    }
1325
1326    fn layout(
1327        &mut self,
1328        view_state: &mut V,
1329        element_state: &mut Self::ElementState,
1330        cx: &mut ViewContext<V>,
1331    ) -> LayoutId {
1332        self.element.layout(view_state, element_state, cx)
1333    }
1334
1335    fn paint(
1336        &mut self,
1337        bounds: Bounds<Pixels>,
1338        view_state: &mut V,
1339        element_state: &mut Self::ElementState,
1340        cx: &mut ViewContext<V>,
1341    ) {
1342        self.element.paint(bounds, view_state, element_state, cx)
1343    }
1344}