div.rs

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