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