node.rs

   1use crate::{
   2    point, px, Action, AnyDrag, AnyElement, AnyTooltip, AnyView, AppContext, BorrowAppContext,
   3    BorrowWindow, Bounds, ClickEvent, DispatchPhase, Element, 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
 550pub struct NodeState {
 551    child_layout_ids: SmallVec<[LayoutId; 4]>,
 552    interactive_state: InteractiveElementState,
 553}
 554
 555impl AsMut<InteractiveElementState> for InteractiveElementState {
 556    fn as_mut(&mut self) -> &mut InteractiveElementState {
 557        self
 558    }
 559}
 560
 561impl<V: 'static> Element<V> for Node<V> {
 562    type ElementState = NodeState;
 563
 564    fn id(&self) -> Option<crate::ElementId> {
 565        None
 566    }
 567
 568    fn initialize(
 569        &mut self,
 570        view_state: &mut V,
 571        previous_element_state: Option<Self::ElementState>,
 572        cx: &mut ViewContext<V>,
 573    ) -> Self::ElementState {
 574        for child in &mut self.children {
 575            child.initialize(view_state, cx);
 576        }
 577        NodeState {
 578            child_layout_ids: SmallVec::new(),
 579            interactive_state: previous_element_state
 580                .map(|s| s.interactive_state)
 581                .unwrap_or_default(),
 582        }
 583    }
 584
 585    fn layout(
 586        &mut self,
 587        view_state: &mut V,
 588        element_state: &mut Self::ElementState,
 589        cx: &mut ViewContext<V>,
 590    ) -> crate::LayoutId {
 591        let mut interactivity = mem::take(&mut self.interactivity);
 592        let layout_id =
 593            interactivity.layout(&mut element_state.interactive_state, cx, |style, cx| {
 594                cx.with_text_style(style.text_style().cloned(), |cx| {
 595                    element_state.child_layout_ids = self
 596                        .children
 597                        .iter_mut()
 598                        .map(|child| child.layout(view_state, cx))
 599                        .collect::<SmallVec<_>>();
 600                    cx.request_layout(&style, element_state.child_layout_ids.iter().copied())
 601                })
 602            });
 603        self.interactivity = interactivity;
 604        layout_id
 605    }
 606
 607    fn paint(
 608        &mut self,
 609        bounds: Bounds<Pixels>,
 610        view_state: &mut V,
 611        element_state: &mut Self::ElementState,
 612        cx: &mut ViewContext<V>,
 613    ) {
 614        let mut interactivity = mem::take(&mut self.interactivity);
 615
 616        let mut child_min = point(Pixels::MAX, Pixels::MAX);
 617        let mut child_max = Point::default();
 618        let content_size = if element_state.child_layout_ids.is_empty() {
 619            bounds.size
 620        } else {
 621            for child_layout_id in &element_state.child_layout_ids {
 622                let child_bounds = cx.layout_bounds(*child_layout_id);
 623                child_min = child_min.min(&child_bounds.origin);
 624                child_max = child_max.max(&child_bounds.lower_right());
 625            }
 626            (child_max - child_min).into()
 627        };
 628
 629        interactivity.paint(
 630            bounds,
 631            content_size,
 632            &mut element_state.interactive_state,
 633            cx,
 634            |style, scroll_offset, cx| {
 635                if style.visibility == Visibility::Hidden {
 636                    return;
 637                }
 638
 639                let z_index = style.z_index.unwrap_or(0);
 640
 641                cx.with_z_index(z_index, |cx| {
 642                    cx.with_z_index(0, |cx| {
 643                        style.paint(bounds, cx);
 644                    });
 645                    cx.with_z_index(1, |cx| {
 646                        cx.with_text_style(style.text_style().cloned(), |cx| {
 647                            cx.with_content_mask(style.overflow_mask(bounds), |cx| {
 648                                cx.with_element_offset(scroll_offset, |cx| {
 649                                    for child in &mut self.children {
 650                                        child.paint(view_state, cx);
 651                                    }
 652                                })
 653                            })
 654                        })
 655                    })
 656                })
 657            },
 658        );
 659        self.interactivity = interactivity;
 660    }
 661}
 662
 663pub enum FocusStatus {
 664    /// The current element is not focused, and does not contain or descend from the focused element.
 665    None,
 666    /// The current element is focused.
 667    Focus,
 668    /// The current element contains the focused element
 669    FocusIn,
 670    /// The current element descends from the focused element
 671    InFocus,
 672}
 673
 674pub struct Interactivity<V> {
 675    active: Option<MouseDownEvent>,
 676    group_active: bool,
 677    hovered: bool,
 678    group_hovered: bool,
 679    focus_status: FocusStatus,
 680    key_context: KeyContext,
 681    focus_handle: Option<FocusHandle>,
 682    scroll_offset: Point<Pixels>,
 683    base_style: StyleRefinement,
 684    focus_style: StyleRefinement,
 685    focus_in_style: StyleRefinement,
 686    in_focus_style: StyleRefinement,
 687    hover_style: StyleRefinement,
 688    group_hover_style: Option<GroupStyle>,
 689    active_style: StyleRefinement,
 690    group_active_style: Option<GroupStyle>,
 691    drag_over_styles: SmallVec<[(TypeId, StyleRefinement); 2]>,
 692    group_drag_over_styles: SmallVec<[(TypeId, GroupStyle); 2]>,
 693    group: Option<SharedString>,
 694    dispatch_context: KeyContext,
 695    mouse_down_listeners: SmallVec<[MouseDownListener<V>; 2]>,
 696    mouse_up_listeners: SmallVec<[MouseUpListener<V>; 2]>,
 697    mouse_move_listeners: SmallVec<[MouseMoveListener<V>; 2]>,
 698    scroll_wheel_listeners: SmallVec<[ScrollWheelListener<V>; 2]>,
 699    key_down_listeners: SmallVec<[KeyDownListener<V>; 2]>,
 700    key_up_listeners: SmallVec<[KeyUpListener<V>; 2]>,
 701    action_listeners: SmallVec<[(TypeId, ActionListener<V>); 8]>,
 702    drop_listeners: SmallVec<[(TypeId, Box<DropListener<V>>); 2]>,
 703    click_listeners: SmallVec<[ClickListener<V>; 2]>,
 704    drag_listener: Option<DragListener<V>>,
 705    hover_listener: Option<HoverListener<V>>,
 706    tooltip_builder: Option<TooltipBuilder<V>>,
 707}
 708
 709#[derive(Default)]
 710pub struct InteractiveElementState {
 711    clicked_state: Arc<Mutex<ElementClickedState>>,
 712    hover_state: Arc<Mutex<bool>>,
 713    pending_mouse_down: Arc<Mutex<Option<MouseDownEvent>>>,
 714    scroll_offset: Option<Arc<Mutex<Point<Pixels>>>>,
 715    active_tooltip: Arc<Mutex<Option<ActiveTooltip>>>,
 716}
 717
 718struct ActiveTooltip {
 719    #[allow(unused)] // used to drop the task
 720    waiting: Option<Task<()>>,
 721    tooltip: Option<AnyTooltip>,
 722}
 723
 724/// Whether or not the element or a group that contains it is clicked by the mouse.
 725#[derive(Copy, Clone, Default, Eq, PartialEq)]
 726struct ElementClickedState {
 727    pub group: bool,
 728    pub element: bool,
 729}
 730
 731impl ElementClickedState {
 732    fn is_clicked(&self) -> bool {
 733        self.group || self.element
 734    }
 735}
 736
 737impl<V> Interactivity<V>
 738where
 739    V: 'static,
 740{
 741    fn compute_style(&self, bounds: Option<Bounds<Pixels>>, cx: &mut ViewContext<V>) -> Style {
 742        let mut style = Style::default();
 743        style.refine(&self.base_style);
 744
 745        match self.focus_status {
 746            FocusStatus::None => {}
 747            FocusStatus::Focus => {
 748                style.refine(&self.focus_style);
 749                style.refine(&self.focus_in_style);
 750                style.refine(&self.in_focus_style);
 751            }
 752            FocusStatus::FocusIn => {
 753                style.refine(&self.focus_in_style);
 754            }
 755            FocusStatus::InFocus => {
 756                style.refine(&self.in_focus_style);
 757            }
 758        }
 759
 760        if let Some(bounds) = bounds {
 761            let mouse_position = cx.mouse_position();
 762            if let Some(group_hover) = self.group_hover_style.as_ref() {
 763                if let Some(group_bounds) = GroupBounds::get(&group_hover.group, cx) {
 764                    if group_bounds.contains_point(&mouse_position) {
 765                        style.refine(&group_hover.style);
 766                    }
 767                }
 768            }
 769            if bounds.contains_point(&mouse_position) {
 770                style.refine(&self.hover_style);
 771            }
 772
 773            if let Some(drag) = cx.active_drag.take() {
 774                for (state_type, group_drag_style) in &self.group_drag_over_styles {
 775                    if let Some(group_bounds) = GroupBounds::get(&group_drag_style.group, cx) {
 776                        if *state_type == drag.view.entity_type()
 777                            && group_bounds.contains_point(&mouse_position)
 778                        {
 779                            style.refine(&group_drag_style.style);
 780                        }
 781                    }
 782                }
 783
 784                for (state_type, drag_over_style) in &self.drag_over_styles {
 785                    if *state_type == drag.view.entity_type()
 786                        && bounds.contains_point(&mouse_position)
 787                    {
 788                        style.refine(drag_over_style);
 789                    }
 790                }
 791
 792                cx.active_drag = Some(drag);
 793            }
 794        }
 795
 796        if self.group_active {
 797            if let Some(group) = self.group_active_style.as_ref() {
 798                style.refine(&group.style)
 799            }
 800        }
 801
 802        if self.active.is_some() {
 803            style.refine(&self.active_style)
 804        }
 805
 806        style
 807    }
 808
 809    fn layout(
 810        &mut self,
 811        element_state: &mut InteractiveElementState,
 812        cx: &mut ViewContext<V>,
 813        f: impl FnOnce(Style, &mut ViewContext<V>) -> LayoutId,
 814    ) -> LayoutId {
 815        let mut style = Style::default();
 816        style.refine(&self.base_style);
 817
 818        if let Some(focus_handle) = self.focus_handle.as_ref() {
 819            if focus_handle.contains_focused(cx) {
 820                style.refine(&self.focus_in_style);
 821            }
 822
 823            if focus_handle.within_focused(cx) {
 824                style.refine(&self.in_focus_style);
 825            }
 826
 827            if focus_handle.is_focused(cx) {
 828                style.refine(&self.focus_style);
 829            }
 830        }
 831
 832        let clicked_state = element_state.clicked_state.lock();
 833        if clicked_state.group {
 834            if let Some(group_style) = self.group_active_style.as_ref() {
 835                style.refine(&group_style.style);
 836            }
 837        }
 838        if clicked_state.element {
 839            style.refine(&self.active_style);
 840        }
 841
 842        f(style, cx)
 843    }
 844
 845    fn paint(
 846        &mut self,
 847        bounds: Bounds<Pixels>,
 848        content_size: Size<Pixels>,
 849        element_state: &mut InteractiveElementState,
 850        cx: &mut ViewContext<V>,
 851        f: impl FnOnce(Style, Point<Pixels>, &mut ViewContext<V>),
 852    ) {
 853        let style = self.compute_style(Some(bounds), cx);
 854
 855        if let Some(mouse_cursor) = style.mouse_cursor {
 856            let hovered = bounds.contains_point(&cx.mouse_position());
 857            if hovered {
 858                cx.set_cursor_style(mouse_cursor);
 859            }
 860        }
 861
 862        for listener in self.mouse_down_listeners.drain(..) {
 863            cx.on_mouse_event(move |state, event: &MouseDownEvent, phase, cx| {
 864                listener(state, event, &bounds, phase, cx);
 865            })
 866        }
 867
 868        for listener in self.mouse_up_listeners.drain(..) {
 869            cx.on_mouse_event(move |state, event: &MouseUpEvent, phase, cx| {
 870                listener(state, event, &bounds, phase, cx);
 871            })
 872        }
 873
 874        for listener in self.mouse_move_listeners.drain(..) {
 875            cx.on_mouse_event(move |state, event: &MouseMoveEvent, phase, cx| {
 876                listener(state, event, &bounds, phase, cx);
 877            })
 878        }
 879
 880        for listener in self.scroll_wheel_listeners.drain(..) {
 881            cx.on_mouse_event(move |state, event: &ScrollWheelEvent, phase, cx| {
 882                listener(state, event, &bounds, phase, cx);
 883            })
 884        }
 885
 886        let hover_group_bounds = self
 887            .group_hover_style
 888            .as_ref()
 889            .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
 890
 891        if let Some(group_bounds) = hover_group_bounds {
 892            let hovered = group_bounds.contains_point(&cx.mouse_position());
 893            cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
 894                if phase == DispatchPhase::Capture {
 895                    if group_bounds.contains_point(&event.position) != hovered {
 896                        cx.notify();
 897                    }
 898                }
 899            });
 900        }
 901
 902        if self.hover_style.is_some()
 903            || (cx.active_drag.is_some() && !self.drag_over_styles.is_empty())
 904        {
 905            let hovered = bounds.contains_point(&cx.mouse_position());
 906            cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
 907                if phase == DispatchPhase::Capture {
 908                    if bounds.contains_point(&event.position) != hovered {
 909                        cx.notify();
 910                    }
 911                }
 912            });
 913        }
 914
 915        if cx.active_drag.is_some() {
 916            let drop_listeners = mem::take(&mut self.drop_listeners);
 917            cx.on_mouse_event(move |view, event: &MouseUpEvent, phase, cx| {
 918                if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 919                    if let Some(drag_state_type) =
 920                        cx.active_drag.as_ref().map(|drag| drag.view.entity_type())
 921                    {
 922                        for (drop_state_type, listener) in &drop_listeners {
 923                            if *drop_state_type == drag_state_type {
 924                                let drag = cx
 925                                    .active_drag
 926                                    .take()
 927                                    .expect("checked for type drag state type above");
 928                                listener(view, drag.view.clone(), cx);
 929                                cx.notify();
 930                                cx.stop_propagation();
 931                            }
 932                        }
 933                    }
 934                }
 935            });
 936        }
 937
 938        let mut element_state: &mut InteractiveElementState = element_state.as_mut();
 939
 940        let click_listeners = mem::take(&mut self.click_listeners);
 941        let drag_listener = mem::take(&mut self.drag_listener);
 942
 943        if !click_listeners.is_empty() || drag_listener.is_some() {
 944            let pending_mouse_down = element_state.pending_mouse_down.clone();
 945            let mouse_down = pending_mouse_down.lock().clone();
 946            if let Some(mouse_down) = mouse_down {
 947                if let Some(drag_listener) = drag_listener {
 948                    let active_state = element_state.clicked_state.clone();
 949
 950                    cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
 951                        if cx.active_drag.is_some() {
 952                            if phase == DispatchPhase::Capture {
 953                                cx.notify();
 954                            }
 955                        } else if phase == DispatchPhase::Bubble
 956                            && bounds.contains_point(&event.position)
 957                            && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
 958                        {
 959                            *active_state.lock() = ElementClickedState::default();
 960                            let cursor_offset = event.position - bounds.origin;
 961                            let drag = drag_listener(view_state, cursor_offset, cx);
 962                            cx.active_drag = Some(drag);
 963                            cx.notify();
 964                            cx.stop_propagation();
 965                        }
 966                    });
 967                }
 968
 969                cx.on_mouse_event(move |view_state, event: &MouseUpEvent, phase, cx| {
 970                    if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 971                        let mouse_click = ClickEvent {
 972                            down: mouse_down.clone(),
 973                            up: event.clone(),
 974                        };
 975                        for listener in &click_listeners {
 976                            listener(view_state, &mouse_click, cx);
 977                        }
 978                    }
 979                    *pending_mouse_down.lock() = None;
 980                });
 981            } else {
 982                cx.on_mouse_event(move |_state, event: &MouseDownEvent, phase, _cx| {
 983                    if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 984                        *pending_mouse_down.lock() = Some(event.clone());
 985                    }
 986                });
 987            }
 988        }
 989
 990        if let Some(hover_listener) = self.hover_listener.take() {
 991            let was_hovered = element_state.hover_state.clone();
 992            let has_mouse_down = element_state.pending_mouse_down.clone();
 993
 994            cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
 995                if phase != DispatchPhase::Bubble {
 996                    return;
 997                }
 998                let is_hovered =
 999                    bounds.contains_point(&event.position) && has_mouse_down.lock().is_none();
1000                let mut was_hovered = was_hovered.lock();
1001
1002                if is_hovered != was_hovered.clone() {
1003                    *was_hovered = is_hovered;
1004                    drop(was_hovered);
1005
1006                    hover_listener(view_state, is_hovered, cx);
1007                }
1008            });
1009        }
1010
1011        if let Some(tooltip_builder) = self.tooltip_builder.take() {
1012            let active_tooltip = element_state.active_tooltip.clone();
1013            let pending_mouse_down = element_state.pending_mouse_down.clone();
1014
1015            cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
1016                if phase != DispatchPhase::Bubble {
1017                    return;
1018                }
1019
1020                let is_hovered =
1021                    bounds.contains_point(&event.position) && pending_mouse_down.lock().is_none();
1022                if !is_hovered {
1023                    active_tooltip.lock().take();
1024                    return;
1025                }
1026
1027                if active_tooltip.lock().is_none() {
1028                    let task = cx.spawn({
1029                        let active_tooltip = active_tooltip.clone();
1030                        let tooltip_builder = tooltip_builder.clone();
1031
1032                        move |view, mut cx| async move {
1033                            cx.background_executor().timer(TOOLTIP_DELAY).await;
1034                            view.update(&mut cx, move |view_state, cx| {
1035                                active_tooltip.lock().replace(ActiveTooltip {
1036                                    waiting: None,
1037                                    tooltip: Some(AnyTooltip {
1038                                        view: tooltip_builder(view_state, cx),
1039                                        cursor_offset: cx.mouse_position() + TOOLTIP_OFFSET,
1040                                    }),
1041                                });
1042                                cx.notify();
1043                            })
1044                            .ok();
1045                        }
1046                    });
1047                    active_tooltip.lock().replace(ActiveTooltip {
1048                        waiting: Some(task),
1049                        tooltip: None,
1050                    });
1051                }
1052            });
1053
1054            if let Some(active_tooltip) = element_state.active_tooltip.lock().as_ref() {
1055                if active_tooltip.tooltip.is_some() {
1056                    cx.active_tooltip = active_tooltip.tooltip.clone()
1057                }
1058            }
1059        }
1060
1061        let active_state = element_state.clicked_state.clone();
1062        if !active_state.lock().is_clicked() {
1063            cx.on_mouse_event(move |_, _: &MouseUpEvent, phase, cx| {
1064                if phase == DispatchPhase::Capture {
1065                    *active_state.lock() = ElementClickedState::default();
1066                    cx.notify();
1067                }
1068            });
1069        } else {
1070            let active_group_bounds = self
1071                .group_active_style
1072                .as_ref()
1073                .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
1074            cx.on_mouse_event(move |_view, down: &MouseDownEvent, phase, cx| {
1075                if phase == DispatchPhase::Bubble {
1076                    let group = active_group_bounds
1077                        .map_or(false, |bounds| bounds.contains_point(&down.position));
1078                    let element = bounds.contains_point(&down.position);
1079                    if group || element {
1080                        *active_state.lock() = ElementClickedState { group, element };
1081                        cx.notify();
1082                    }
1083                }
1084            });
1085        }
1086
1087        let overflow = style.overflow;
1088        if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
1089            let scroll_offset = element_state
1090                .scroll_offset
1091                .get_or_insert_with(Arc::default)
1092                .clone();
1093            let line_height = cx.line_height();
1094            let scroll_max = (content_size - bounds.size).max(&Size::default());
1095
1096            cx.on_mouse_event(move |_, event: &ScrollWheelEvent, phase, cx| {
1097                if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
1098                    let mut scroll_offset = scroll_offset.lock();
1099                    let old_scroll_offset = *scroll_offset;
1100                    let delta = event.delta.pixel_delta(line_height);
1101
1102                    if overflow.x == Overflow::Scroll {
1103                        scroll_offset.x =
1104                            (scroll_offset.x + delta.x).clamp(-scroll_max.width, px(0.));
1105                    }
1106
1107                    if overflow.y == Overflow::Scroll {
1108                        scroll_offset.y =
1109                            (scroll_offset.y + delta.y).clamp(-scroll_max.height, px(0.));
1110                    }
1111
1112                    if *scroll_offset != old_scroll_offset {
1113                        cx.notify();
1114                        cx.stop_propagation();
1115                    }
1116                }
1117            });
1118        }
1119
1120        if let Some(group) = self.group.clone() {
1121            GroupBounds::push(group, bounds, cx);
1122        }
1123
1124        cx.with_key_dispatch(
1125            self.key_context.clone(),
1126            self.focus_handle.clone(),
1127            |_, cx| f(style, self.scroll_offset, cx),
1128        );
1129
1130        if let Some(group) = self.group.as_ref() {
1131            GroupBounds::pop(group, cx);
1132        }
1133    }
1134}
1135
1136impl<V: 'static> Default for Interactivity<V> {
1137    fn default() -> Self {
1138        Self {
1139            active: None,
1140            group_active: false,
1141            hovered: false,
1142            group_hovered: false,
1143            focus_status: FocusStatus::None,
1144            key_context: KeyContext::default(),
1145            focus_handle: None,
1146            scroll_offset: Point::default(),
1147            base_style: StyleRefinement::default(),
1148            focus_style: StyleRefinement::default(),
1149            focus_in_style: StyleRefinement::default(),
1150            in_focus_style: StyleRefinement::default(),
1151            hover_style: StyleRefinement::default(),
1152            group_hover_style: None,
1153            active_style: StyleRefinement::default(),
1154            group_active_style: None,
1155            drag_over_styles: SmallVec::new(),
1156            group_drag_over_styles: SmallVec::new(),
1157            group: None,
1158            dispatch_context: KeyContext::default(),
1159            mouse_down_listeners: SmallVec::new(),
1160            mouse_up_listeners: SmallVec::new(),
1161            mouse_move_listeners: SmallVec::new(),
1162            scroll_wheel_listeners: SmallVec::new(),
1163            key_down_listeners: SmallVec::new(),
1164            key_up_listeners: SmallVec::new(),
1165            action_listeners: SmallVec::new(),
1166            drop_listeners: SmallVec::new(),
1167            click_listeners: SmallVec::new(),
1168            drag_listener: None,
1169            hover_listener: None,
1170            tooltip_builder: None,
1171        }
1172    }
1173}
1174
1175#[derive(Default)]
1176pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
1177
1178impl GroupBounds {
1179    pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
1180        cx.default_global::<Self>()
1181            .0
1182            .get(name)
1183            .and_then(|bounds_stack| bounds_stack.last())
1184            .cloned()
1185    }
1186
1187    pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
1188        cx.default_global::<Self>()
1189            .0
1190            .entry(name)
1191            .or_default()
1192            .push(bounds);
1193    }
1194
1195    pub fn pop(name: &SharedString, cx: &mut AppContext) {
1196        cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
1197    }
1198}
1199
1200pub struct Focusable<V, E> {
1201    focusability: Focusability<V>,
1202    view_type: PhantomData<V>,
1203    element: E,
1204}
1205
1206pub struct Focusability<V> {
1207    focus_handle: Option<FocusHandle>,
1208    focus_listeners: FocusListeners<V>,
1209    focus_style: StyleRefinement,
1210    focus_in_style: StyleRefinement,
1211    in_focus_style: StyleRefinement,
1212}
1213
1214impl<V, E> FocusableComponent<V> for Focusable<V, E> {
1215    fn focusability(&mut self) -> &mut Focusability<V> {
1216        &mut self.focusability
1217    }
1218}
1219
1220impl<V, E> InteractiveComponent<V> for Focusable<V, E>
1221where
1222    V: 'static,
1223    E: InteractiveComponent<V>,
1224{
1225    fn interactivity(&mut self) -> &mut Interactivity<V> {
1226        self.element.interactivity()
1227    }
1228}
1229
1230impl<V: 'static, E: StatefulInteractiveComponent<V, E>> StatefulInteractiveComponent<V, E>
1231    for Focusable<V, E>
1232{
1233}
1234
1235impl<V, E> Element<V> for Focusable<V, E>
1236where
1237    V: 'static,
1238    E: Element<V>,
1239{
1240    type ElementState = E::ElementState;
1241
1242    fn id(&self) -> Option<crate::ElementId> {
1243        todo!()
1244    }
1245
1246    fn initialize(
1247        &mut self,
1248        view_state: &mut V,
1249        element_state: Option<Self::ElementState>,
1250        cx: &mut ViewContext<V>,
1251    ) -> Self::ElementState {
1252        todo!()
1253    }
1254
1255    fn layout(
1256        &mut self,
1257        view_state: &mut V,
1258        element_state: &mut Self::ElementState,
1259        cx: &mut ViewContext<V>,
1260    ) -> LayoutId {
1261        todo!()
1262    }
1263
1264    fn paint(
1265        &mut self,
1266        bounds: Bounds<Pixels>,
1267        view_state: &mut V,
1268        element_state: &mut Self::ElementState,
1269        cx: &mut ViewContext<V>,
1270    ) {
1271        todo!()
1272    }
1273}
1274
1275pub struct Stateful<V, E> {
1276    id: SharedString,
1277    view_type: PhantomData<V>,
1278    element: E,
1279}
1280
1281impl<V, E> StatefulInteractiveComponent<V, E> for Stateful<V, E>
1282where
1283    V: 'static,
1284    E: Element<V>,
1285    Self: InteractiveComponent<V>,
1286{
1287}
1288
1289impl<V, E> InteractiveComponent<V> for Stateful<V, E>
1290where
1291    V: 'static,
1292    E: InteractiveComponent<V>,
1293{
1294    fn interactivity(&mut self) -> &mut Interactivity<V> {
1295        self.element.interactivity()
1296    }
1297}
1298
1299impl<V, E: FocusableComponent<V>> FocusableComponent<V> for Stateful<V, E> {
1300    fn focusability(&mut self) -> &mut Focusability<V> {
1301        self.element.focusability()
1302    }
1303}
1304
1305impl<V, E> Element<V> for Stateful<V, E>
1306where
1307    V: 'static,
1308    E: Element<V>,
1309{
1310    type ElementState = InteractiveElementState;
1311
1312    fn id(&self) -> Option<crate::ElementId> {
1313        todo!()
1314    }
1315
1316    fn initialize(
1317        &mut self,
1318        view_state: &mut V,
1319        element_state: Option<Self::ElementState>,
1320        cx: &mut ViewContext<V>,
1321    ) -> Self::ElementState {
1322        todo!()
1323    }
1324
1325    fn layout(
1326        &mut self,
1327        view_state: &mut V,
1328        element_state: &mut Self::ElementState,
1329        cx: &mut ViewContext<V>,
1330    ) -> LayoutId {
1331        todo!()
1332    }
1333
1334    fn paint(
1335        &mut self,
1336        bounds: Bounds<Pixels>,
1337        view_state: &mut V,
1338        element_state: &mut Self::ElementState,
1339        cx: &mut ViewContext<V>,
1340    ) {
1341        todo!()
1342    }
1343}