div.rs

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