diff --git a/crates/collab_ui/src/face_pile.rs b/crates/collab_ui/src/face_pile.rs index eb20814ca75bf48a67ab26f5fc9fb276405754e2..cc47a057ac869bea6ef17cad92f46a0df03934ed 100644 --- a/crates/collab_ui/src/face_pile.rs +++ b/crates/collab_ui/src/face_pile.rs @@ -37,8 +37,8 @@ impl RenderOnce for FacePile { } impl ParentElement for FacePile { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - &mut self.faces + fn extend(&mut self, elements: impl IntoIterator) { + self.faces.extend(elements); } } diff --git a/crates/collab_ui/src/notifications/collab_notification.rs b/crates/collab_ui/src/notifications/collab_notification.rs index 8157bc1318dac52710732880d565e4914d01d8de..69d26e50fd3e1948d5c9b1e6682bfb71eddffdc2 100644 --- a/crates/collab_ui/src/notifications/collab_notification.rs +++ b/crates/collab_ui/src/notifications/collab_notification.rs @@ -26,8 +26,8 @@ impl CollabNotification { } impl ParentElement for CollabNotification { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - &mut self.children + fn extend(&mut self, elements: impl Iterator) { + self.children.extend(elements) } } diff --git a/crates/gpui/src/action.rs b/crates/gpui/src/action.rs index 9caa0da4823f64f5c30c32619a7b6950b305e676..c6ea705b570167d3c994cc821967bdee6df1f7f6 100644 --- a/crates/gpui/src/action.rs +++ b/crates/gpui/src/action.rs @@ -40,14 +40,25 @@ use std::any::{Any, TypeId}; /// register_action!(Paste); /// ``` pub trait Action: 'static { + /// Clone the action into a new box fn boxed_clone(&self) -> Box; + + /// Cast the action to the any type fn as_any(&self) -> &dyn Any; + + /// Do a partial equality check on this action and the other fn partial_eq(&self, action: &dyn Action) -> bool; + + /// Get the name of this action, for displaying in UI fn name(&self) -> &str; + /// Get the name of this action for debugging fn debug_name() -> &'static str where Self: Sized; + + /// Build this action from a JSON value. This is used to construct actions from the keymap. + /// A value of `{}` will be passed for actions that don't have any parameters. fn build(value: serde_json::Value) -> Result> where Self: Sized; @@ -62,6 +73,7 @@ impl std::fmt::Debug for dyn Action { } impl dyn Action { + /// Get the type id of this action pub fn type_id(&self) -> TypeId { self.as_any().type_id() } @@ -170,6 +182,7 @@ impl ActionRegistry { macro_rules! actions { ($namespace:path, [ $($name:ident),* $(,)? ]) => { $( + /// The `$name` action see [`gpui::actions!`] #[derive(::std::cmp::PartialEq, ::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug, gpui::private::serde_derive::Deserialize)] #[serde(crate = "gpui::private::serde")] pub struct $name; diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs index d898d865164a61c9935f8fe1ed5e957a28026ee5..7b349d92568e72b9b4929655e93dd1683636964e 100644 --- a/crates/gpui/src/app.rs +++ b/crates/gpui/src/app.rs @@ -1,5 +1,3 @@ -#![deny(missing_docs)] - mod async_context; mod entity_map; mod model_context; diff --git a/crates/gpui/src/app/test_context.rs b/crates/gpui/src/app/test_context.rs index 139d52b6404d3ae022c0611c607cd757934467b8..053897ee7f9aa46c2ab453077b59c408a3ec394c 100644 --- a/crates/gpui/src/app/test_context.rs +++ b/crates/gpui/src/app/test_context.rs @@ -1,5 +1,3 @@ -#![deny(missing_docs)] - use crate::{ Action, AnyElement, AnyView, AnyWindowHandle, AppCell, AppContext, AsyncAppContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem, Context, Entity, EventEmitter, diff --git a/crates/gpui/src/assets.rs b/crates/gpui/src/assets.rs index 39c8562b69703a959fcbd3ad75bc8a6601b0a839..b5e3735eb585914c8e88c47660f82c214059e041 100644 --- a/crates/gpui/src/assets.rs +++ b/crates/gpui/src/assets.rs @@ -8,8 +8,12 @@ use std::{ sync::atomic::{AtomicUsize, Ordering::SeqCst}, }; +/// A source of assets for this app to use. pub trait AssetSource: 'static + Send + Sync { + /// Load the given asset from the source path. fn load(&self, path: &str) -> Result>; + + /// List the assets at the given path. fn list(&self, path: &str) -> Result>; } @@ -26,15 +30,19 @@ impl AssetSource for () { } } +/// A unique identifier for the image cache #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct ImageId(usize); +/// A cached and processed image. pub struct ImageData { + /// The ID associated with this image pub id: ImageId, data: ImageBuffer, Vec>, } impl ImageData { + /// Create a new image from the given data. pub fn new(data: ImageBuffer, Vec>) -> Self { static NEXT_ID: AtomicUsize = AtomicUsize::new(0); @@ -44,10 +52,12 @@ impl ImageData { } } + /// Convert this image into a byte slice. pub fn as_bytes(&self) -> &[u8] { &self.data } + /// Get the size of this image, in pixels pub fn size(&self) -> Size { let (width, height) = self.data.dimensions(); size(width.into(), height.into()) diff --git a/crates/gpui/src/color.rs b/crates/gpui/src/color.rs index 23fcc25f6aeed436309a3670393d4cbca10536e6..e2d6d199f82feae8ea0b079370d8bbf817ae6348 100644 --- a/crates/gpui/src/color.rs +++ b/crates/gpui/src/color.rs @@ -2,6 +2,7 @@ use anyhow::bail; use serde::de::{self, Deserialize, Deserializer, Visitor}; use std::fmt; +/// Convert an RGB hex color code number to a color type pub fn rgb>(hex: u32) -> C { let r = ((hex >> 16) & 0xFF) as f32 / 255.0; let g = ((hex >> 8) & 0xFF) as f32 / 255.0; @@ -9,6 +10,7 @@ pub fn rgb>(hex: u32) -> C { Rgba { r, g, b, a: 1.0 }.into() } +/// Convert an RGBA hex color code number to [`Rgba`] pub fn rgba(hex: u32) -> Rgba { let r = ((hex >> 24) & 0xFF) as f32 / 255.0; let g = ((hex >> 16) & 0xFF) as f32 / 255.0; @@ -17,11 +19,16 @@ pub fn rgba(hex: u32) -> Rgba { Rgba { r, g, b, a } } +/// An RGBA color #[derive(PartialEq, Clone, Copy, Default)] pub struct Rgba { + /// The red component of the color, in the range 0.0 to 1.0 pub r: f32, + /// The green component of the color, in the range 0.0 to 1.0 pub g: f32, + /// The blue component of the color, in the range 0.0 to 1.0 pub b: f32, + /// The alpha component of the color, in the range 0.0 to 1.0 pub a: f32, } @@ -32,6 +39,8 @@ impl fmt::Debug for Rgba { } impl Rgba { + /// Create a new [`Rgba`] color by blending this and another color together + /// TODO: find the source for this algorithm pub fn blend(&self, other: Rgba) -> Self { if other.a >= 1.0 { other @@ -165,12 +174,20 @@ impl TryFrom<&'_ str> for Rgba { } } +/// An HSLA color #[derive(Default, Copy, Clone, Debug)] #[repr(C)] pub struct Hsla { + /// Hue, in a range from 0 to 1 pub h: f32, + + /// Saturation, in a range from 0 to 1 pub s: f32, + + /// Lightness, in a range from 0 to 1 pub l: f32, + + /// Alpha, in a range from 0 to 1 pub a: f32, } @@ -203,38 +220,9 @@ impl Ord for Hsla { } } -impl Hsla { - pub fn to_rgb(self) -> Rgba { - self.into() - } - - pub fn red() -> Self { - red() - } - - pub fn green() -> Self { - green() - } - - pub fn blue() -> Self { - blue() - } - - pub fn black() -> Self { - black() - } - - pub fn white() -> Self { - white() - } - - pub fn transparent_black() -> Self { - transparent_black() - } -} - impl Eq for Hsla {} +/// Construct an [`Hsla`] object from plain values pub fn hsla(h: f32, s: f32, l: f32, a: f32) -> Hsla { Hsla { h: h.clamp(0., 1.), @@ -244,6 +232,7 @@ pub fn hsla(h: f32, s: f32, l: f32, a: f32) -> Hsla { } } +/// Pure black in [`Hsla`] pub fn black() -> Hsla { Hsla { h: 0., @@ -253,6 +242,7 @@ pub fn black() -> Hsla { } } +/// Transparent black in [`Hsla`] pub fn transparent_black() -> Hsla { Hsla { h: 0., @@ -262,6 +252,7 @@ pub fn transparent_black() -> Hsla { } } +/// Pure white in [`Hsla`] pub fn white() -> Hsla { Hsla { h: 0., @@ -271,6 +262,7 @@ pub fn white() -> Hsla { } } +/// The color red in [`Hsla`] pub fn red() -> Hsla { Hsla { h: 0., @@ -280,6 +272,7 @@ pub fn red() -> Hsla { } } +/// The color blue in [`Hsla`] pub fn blue() -> Hsla { Hsla { h: 0.6, @@ -289,6 +282,7 @@ pub fn blue() -> Hsla { } } +/// The color green in [`Hsla`] pub fn green() -> Hsla { Hsla { h: 0.33, @@ -298,6 +292,7 @@ pub fn green() -> Hsla { } } +/// The color yellow in [`Hsla`] pub fn yellow() -> Hsla { Hsla { h: 0.16, @@ -308,6 +303,41 @@ pub fn yellow() -> Hsla { } impl Hsla { + /// Converts this HSLA color to an RGBA color. + pub fn to_rgb(self) -> Rgba { + self.into() + } + + /// The color red + pub fn red() -> Self { + red() + } + + /// The color green + pub fn green() -> Self { + green() + } + + /// The color blue + pub fn blue() -> Self { + blue() + } + + /// The color black + pub fn black() -> Self { + black() + } + + /// The color white + pub fn white() -> Self { + white() + } + + /// The color transparent black + pub fn transparent_black() -> Self { + transparent_black() + } + /// Returns true if the HSLA color is fully transparent, false otherwise. pub fn is_transparent(&self) -> bool { self.a == 0.0 @@ -339,6 +369,7 @@ impl Hsla { } } + /// Returns a new HSLA color with the same hue, and lightness, but with no saturation. pub fn grayscale(&self) -> Self { Hsla { h: self.h, diff --git a/crates/gpui/src/element.rs b/crates/gpui/src/element.rs index 47fb7241aba03890120d57312361a0c004237b07..0c98820d306c7433ab7d3170a95c923806977461 100644 --- a/crates/gpui/src/element.rs +++ b/crates/gpui/src/element.rs @@ -1,3 +1,39 @@ +//! Elements are the workhorses of GPUI. They are responsible for laying out and painting all of +//! the contents of a window. Elements form a tree and are laid out according to the web layout +//! standards as implemented by [taffy](https://github.com/DioxusLabs/taffy). Most of the time, +//! you won't need to interact with this module or these APIs directly. Elements provide their +//! own APIs and GPUI, or other element implementation, uses the APIs in this module to convert +//! that element tree into the pixels you see on the screen. +//! +//! # Element Basics +//! +//! Elements are constructed by calling [`Render::render()`] on the root view of the window, which +//! which recursively constructs the element tree from the current state of the application. +//! These elements are then laid out by Taffy, and painted to the screen according to their own +//! implementation of [`Element::paint()`]. Before the start of the next frame, the entire element +//! tree and any callbacks they have registered with GPUI are dropped and the process repeats. +//! +//! But some state is too simple and voluminous to store in every view that needs it, e.g. +//! whether a hover has been started or not. For this, GPUI provides the [`Element::State`], type. +//! If an element returns an [`ElementId`] from [`IntoElement::element_id()`], and that element id +//! appears in the same place relative to other views and ElementIds in the frame, then the previous +//! frame's state will be passed to the element's layout and paint methods. +//! +//! # Implementing your own elements +//! +//! Elements are intended to be the low level, imperative API to GPUI. They are responsible for upholding, +//! or breaking, GPUI's features as they deem necessary. As an example, most GPUI elements are expected +//! to stay in the bounds that their parent element gives them. But with [`WindowContext::break_content_mask`], +//! you can ignore this restriction and paint anywhere inside of the window's bounds. This is useful for overlays +//! and popups and anything else that shows up 'on top' of other elements. +//! With great power, comes great responsibility. +//! +//! However, most of the time, you won't need to implement your own elements. GPUI provides a number of +//! elements that should cover most common use cases out of the box and it's recommended that you use those +//! to construct `components`, using the `RenderOnce` trait and the `#[derive(IntoElement)]` macro. Only implement +//! elements when you need to take manual control of the layout and painting process, such as when using +//! your own custom layout algorithm or rendering a code editor. + use crate::{ util::FluentBuilder, ArenaBox, AvailableSpace, BorrowWindow, Bounds, ElementId, LayoutId, Pixels, Point, Size, ViewContext, WindowContext, ELEMENT_ARENA, @@ -7,20 +43,27 @@ pub(crate) use smallvec::SmallVec; use std::{any::Any, fmt::Debug}; /// Implemented by types that participate in laying out and painting the contents of a window. -/// Elements form a tree and are laid out according to web-based layout rules. -/// Rather than calling methods on implementers of this trait directly, you'll usually call `into_any` to convert them into an AnyElement, which manages state internally. -/// You can create custom elements by implementing this trait. +/// Elements form a tree and are laid out according to web-based layout rules, as implemented by Taffy. +/// You can create custom elements by implementing this trait, see the module-level documentation +/// for more details. pub trait Element: 'static + IntoElement { + /// The type of state to store for this element between frames. See the module-level documentation + /// for details. type State: 'static; + /// Before an element can be painted, we need to know where it's going to be and how big it is. + /// Use this method to request a layout from Taffy and initialize the element's state. fn request_layout( &mut self, state: Option, cx: &mut WindowContext, ) -> (LayoutId, Self::State); + /// Once layout has been completed, this method will be called to paint the element to the screen. + /// The state argument is the same state that was returned from [`Element::request_layout()`]. fn paint(&mut self, bounds: Bounds, state: &mut Self::State, cx: &mut WindowContext); + /// Convert this element into a dynamically-typed [`AnyElement`]. fn into_any(self) -> AnyElement { AnyElement::new(self) } @@ -29,6 +72,7 @@ pub trait Element: 'static + IntoElement { /// Implemented by any type that can be converted into an element. pub trait IntoElement: Sized { /// The specific type of element into which the implementing type is converted. + /// Useful for converting other types into elements automatically, like Strings type Element: Element; /// The [`ElementId`] of self once converted into an [`Element`]. @@ -81,7 +125,10 @@ pub trait IntoElement: Sized { impl FluentBuilder for T {} +/// An object that can be drawn to the screen. This is the trait that distinguishes `Views` from +/// models. Views are drawn to the screen and care about the current window's state, models are not and do not. pub trait Render: 'static + Sized { + /// Render this view into an element tree. fn render(&mut self, cx: &mut ViewContext) -> impl IntoElement; } @@ -92,35 +139,49 @@ impl Render for () { } /// You can derive [`IntoElement`] on any type that implements this trait. -/// It is used to allow views to be expressed in terms of abstract data. +/// It is used to construct reusable `components` out of plain data. Think of +/// components as a recipe for a certain pattern of elements. RenderOnce allows +/// you to invoke this pattern, without breaking the fluent builder pattern of +/// the element APIs. pub trait RenderOnce: 'static { + /// Render this component into an element tree. Note that this method + /// takes ownership of self, as compared to [`Render::render()`] method + /// which takes a mutable reference. fn render(self, cx: &mut WindowContext) -> impl IntoElement; } +/// This is a helper trait to provide a uniform interface for constructing elements that +/// can accept any number of any kind of child elements pub trait ParentElement { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]>; + /// Extend this element's children with the given child elements. + fn extend(&mut self, elements: impl Iterator); + /// Add a single child element to this element. fn child(mut self, child: impl IntoElement) -> Self where Self: Sized, { - self.children_mut().push(child.into_element().into_any()); + self.extend(std::iter::once(child.into_element().into_any())); self } + /// Add multiple child elements to this element. fn children(mut self, children: impl IntoIterator) -> Self where Self: Sized, { - self.children_mut() - .extend(children.into_iter().map(|child| child.into_any_element())); + self.extend(children.into_iter().map(|child| child.into_any_element())); self } } +/// An element for rendering components. An implementation detail of the [`IntoElement`] derive macro +/// for [`RenderOnce`] +#[doc(hidden)] pub struct Component(Option); impl Component { + /// Create a new component from the given RenderOnce type. pub fn new(component: C) -> Self { Component(Some(component)) } @@ -156,8 +217,9 @@ impl IntoElement for Component { } } +/// A globally unique identifier for an element, used to track state across frames. #[derive(Deref, DerefMut, Default, Clone, Debug, Eq, PartialEq, Hash)] -pub struct GlobalElementId(SmallVec<[ElementId; 32]>); +pub(crate) struct GlobalElementId(SmallVec<[ElementId; 32]>); trait ElementObject { fn element_id(&self) -> Option; @@ -180,7 +242,8 @@ trait ElementObject { ); } -pub struct DrawableElement { +/// A wrapper around an implementer of [`Element`] that allows it to be drawn in a window. +pub(crate) struct DrawableElement { element: Option, phase: ElementDrawPhase, } @@ -363,10 +426,11 @@ where } } +/// A dynamically typed element that can be used to store any element type. pub struct AnyElement(ArenaBox); impl AnyElement { - pub fn new(element: E) -> Self + pub(crate) fn new(element: E) -> Self where E: 'static + Element, E::State: Any, @@ -377,10 +441,13 @@ impl AnyElement { AnyElement(element) } + /// Request the layout ID of the element stored in this `AnyElement`. + /// Used for laying out child elements in a parent element. pub fn request_layout(&mut self, cx: &mut WindowContext) -> LayoutId { self.0.request_layout(cx) } + /// Paints the element stored in this `AnyElement`. pub fn paint(&mut self, cx: &mut WindowContext) { self.0.paint(cx) } @@ -404,6 +471,7 @@ impl AnyElement { self.0.draw(origin, available_space, cx) } + /// Returns the element ID of the element stored in this `AnyElement`, if any. pub fn inner_id(&self) -> Option { self.0.element_id() } diff --git a/crates/gpui/src/elements/canvas.rs b/crates/gpui/src/elements/canvas.rs index 767417ae40100a7ef3ff8ea6fecea0a4f9eca53f..3cfd45b94d0d3d084488d1c5440f359ece8aae65 100644 --- a/crates/gpui/src/elements/canvas.rs +++ b/crates/gpui/src/elements/canvas.rs @@ -2,6 +2,8 @@ use refineable::Refineable as _; use crate::{Bounds, Element, IntoElement, Pixels, Style, StyleRefinement, Styled, WindowContext}; +/// Construct a canvas element with the given paint callback. +/// Useful for adding short term custom drawing to a view. pub fn canvas(callback: impl 'static + FnOnce(&Bounds, &mut WindowContext)) -> Canvas { Canvas { paint_callback: Some(Box::new(callback)), @@ -9,6 +11,8 @@ pub fn canvas(callback: impl 'static + FnOnce(&Bounds, &mut WindowContex } } +/// A canvas element, meant for accessing the low level paint API without defining a whole +/// custom element pub struct Canvas { paint_callback: Option, &mut WindowContext)>>, style: StyleRefinement, diff --git a/crates/gpui/src/elements/div.rs b/crates/gpui/src/elements/div.rs index f0baf23ab1d26f815a9ad539ad20befad987518d..6bfdbde10f9457df97eadb8e4c73355e7beb17ee 100644 --- a/crates/gpui/src/elements/div.rs +++ b/crates/gpui/src/elements/div.rs @@ -1,3 +1,27 @@ +//! Div is the central, reusable element that most GPUI trees will be built from. +//! It functions as a container for other elements, and provides a number of +//! useful features for laying out and styling its children as well as binding +//! mouse events and action handlers. It is meant to be similar to the HTML
+//! element, but for GPUI. +//! +//! # Build your own div +//! +//! GPUI does not directly provide APIs for stateful, multi step events like `click` +//! and `drag`. We want GPUI users to be able to build their own abstractions for +//! their own needs. However, as a UI framework, we're also obliged to provide some +//! building blocks to make the process of building your own elements easier. +//! For this we have the [`Interactivity`] and the [`StyleRefinement`] structs, as well +//! as several associated traits. Together, these provide the full suite of Dom-like events +//! and Tailwind-like styling that you can use to build your own custom elements. Div is +//! constructed by combining these two systems into an all-in-one element. +//! +//! # Capturing and bubbling +//! +//! Note that while event dispatch in GPUI uses similar names and concepts to the web +//! even API, the details are very different. See the documentation in [TODO +//! DOCUMENT EVENT DISPATCH SOMEWHERE IN WINDOW CONTEXT] for more details +//! + use crate::{ point, px, Action, AnyDrag, AnyElement, AnyTooltip, AnyView, AppContext, BorrowAppContext, BorrowWindow, Bounds, ClickEvent, DispatchPhase, Element, ElementId, FocusHandle, IntoElement, @@ -26,18 +50,28 @@ use util::ResultExt; const DRAG_THRESHOLD: f64 = 2.; pub(crate) const TOOLTIP_DELAY: Duration = Duration::from_millis(500); +/// The styling information for a given group. pub struct GroupStyle { + /// The identifier for this group. pub group: SharedString, + + /// The specific style refinement that this group would apply + /// to its children. pub style: Box, } +/// An event for when a drag is moving over this element, with the given state type. pub struct DragMoveEvent { + /// The mouse move event that triggered this drag move event. pub event: MouseMoveEvent, + + /// The bounds of this element. pub bounds: Bounds, drag: PhantomData, } impl DragMoveEvent { + /// Returns the drag state for this event. pub fn drag<'b>(&self, cx: &'b AppContext) -> &'b T { cx.active_drag .as_ref() @@ -47,6 +81,10 @@ impl DragMoveEvent { } impl Interactivity { + /// Bind the given callback to the mouse down event for the given mouse button, during the bubble phase + /// The imperative API equivalent of [`InteractiveElement::on_mouse_down`] + /// + /// See [`ViewContext::listener()`] to get access to the view state from this callback pub fn on_mouse_down( &mut self, button: MouseButton, @@ -63,6 +101,10 @@ impl Interactivity { })); } + /// Bind the given callback to the mouse down event for any button, during the capture phase + /// The imperative API equivalent of [`InteractiveElement::capture_any_mouse_down`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn capture_any_mouse_down( &mut self, listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static, @@ -75,6 +117,10 @@ impl Interactivity { })); } + /// Bind the given callback to the mouse down event for any button, during the bubble phase + /// the imperative API equivalent to [`InteractiveElement::on_any_mouse_down()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_any_mouse_down( &mut self, listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static, @@ -87,6 +133,10 @@ impl Interactivity { })); } + /// Bind the given callback to the mouse up event for the given button, during the bubble phase + /// the imperative API equivalent to [`InteractiveElement::on_mouse_up()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_mouse_up( &mut self, button: MouseButton, @@ -103,6 +153,10 @@ impl Interactivity { })); } + /// Bind the given callback to the mouse up event for any button, during the capture phase + /// the imperative API equivalent to [`InteractiveElement::capture_any_mouse_up()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn capture_any_mouse_up( &mut self, listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static, @@ -115,6 +169,10 @@ impl Interactivity { })); } + /// Bind the given callback to the mouse up event for any button, during the bubble phase + /// the imperative API equivalent to [`InteractiveElement::on_any_mouse_up()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_any_mouse_up( &mut self, listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static, @@ -127,6 +185,11 @@ impl Interactivity { })); } + /// Bind the given callback to the mouse down event, on any button, during the capture phase, + /// when the mouse is outside of the bounds of this element. + /// The imperative API equivalent to [`InteractiveElement::on_mouse_down_out()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_mouse_down_out( &mut self, listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static, @@ -140,6 +203,11 @@ impl Interactivity { })); } + /// Bind the given callback to the mouse up event, for the given button, during the capture phase, + /// when the mouse is outside of the bounds of this element. + /// The imperative API equivalent to [`InteractiveElement::on_mouse_up_out()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_mouse_up_out( &mut self, button: MouseButton, @@ -156,6 +224,10 @@ impl Interactivity { })); } + /// Bind the given callback to the mouse move event, during the bubble phase + /// The imperative API equivalent to [`InteractiveElement::on_mouse_move()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_mouse_move( &mut self, listener: impl Fn(&MouseMoveEvent, &mut WindowContext) + 'static, @@ -168,6 +240,13 @@ impl Interactivity { })); } + /// Bind the given callback to the mouse drag event of the given type. Note that this + /// will be called for all move events, inside or outside of this element, as long as the + /// drag was started with this element under the mouse. Useful for implementing draggable + /// UIs that don't conform to a drag and drop style interaction, like resizing. + /// The imperative API equivalent to [`InteractiveElement::on_drag_move()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_drag_move( &mut self, listener: impl Fn(&DragMoveEvent, &mut WindowContext) + 'static, @@ -194,6 +273,10 @@ impl Interactivity { })); } + /// Bind the given callback to scroll wheel events during the bubble phase + /// The imperative API equivalent to [`InteractiveElement::on_scroll_wheel()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_scroll_wheel( &mut self, listener: impl Fn(&ScrollWheelEvent, &mut WindowContext) + 'static, @@ -206,6 +289,10 @@ impl Interactivity { })); } + /// Bind the given callback to an action dispatch during the capture phase + /// The imperative API equivalent to [`InteractiveElement::capture_action()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn capture_action( &mut self, listener: impl Fn(&A, &mut WindowContext) + 'static, @@ -221,6 +308,10 @@ impl Interactivity { )); } + /// Bind the given callback to an action dispatch during the bubble phase + /// The imperative API equivalent to [`InteractiveElement::on_action()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_action(&mut self, listener: impl Fn(&A, &mut WindowContext) + 'static) { self.action_listeners.push(( TypeId::of::(), @@ -233,6 +324,12 @@ impl Interactivity { )); } + /// Bind the given callback to an action dispatch, based on a dynamic action parameter + /// instead of a type parameter. Useful for component libraries that want to expose + /// action bindings to their users. + /// The imperative API equivalent to [`InteractiveElement::on_boxed_action()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_boxed_action( &mut self, action: &dyn Action, @@ -249,6 +346,10 @@ impl Interactivity { )); } + /// Bind the given callback to key down events during the bubble phase + /// The imperative API equivalent to [`InteractiveElement::on_key_down()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_key_down(&mut self, listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static) { self.key_down_listeners .push(Box::new(move |event, phase, cx| { @@ -258,6 +359,10 @@ impl Interactivity { })); } + /// Bind the given callback to key down events during the capture phase + /// The imperative API equivalent to [`InteractiveElement::capture_key_down()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn capture_key_down( &mut self, listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static, @@ -270,6 +375,10 @@ impl Interactivity { })); } + /// Bind the given callback to key up events during the bubble phase + /// The imperative API equivalent to [`InteractiveElement::on_key_up()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) { self.key_up_listeners .push(Box::new(move |event, phase, cx| { @@ -279,6 +388,10 @@ impl Interactivity { })); } + /// Bind the given callback to key up events during the capture phase + /// The imperative API equivalent to [`InteractiveElement::on_key_up()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn capture_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) { self.key_up_listeners .push(Box::new(move |event, phase, cx| { @@ -288,6 +401,10 @@ impl Interactivity { })); } + /// Bind the given callback to drop events of the given type, whether or not the drag started on this element + /// The imperative API equivalent to [`InteractiveElement::on_drop()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_drop(&mut self, listener: impl Fn(&T, &mut WindowContext) + 'static) { self.drop_listeners.push(( TypeId::of::(), @@ -297,10 +414,16 @@ impl Interactivity { )); } + /// Use the given predicate to determine whether or not a drop event should be dispatched to this element + /// The imperative API equivalent to [`InteractiveElement::can_drop()`] pub fn can_drop(&mut self, predicate: impl Fn(&dyn Any, &mut WindowContext) -> bool + 'static) { self.can_drop_predicate = Some(Box::new(predicate)); } + /// Bind the given callback to click events of this element + /// The imperative API equivalent to [`InteractiveElement::on_click()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut WindowContext) + 'static) where Self: Sized, @@ -309,6 +432,12 @@ impl Interactivity { .push(Box::new(move |event, cx| listener(event, cx))); } + /// On drag initiation, this callback will be used to create a new view to render the dragged value for a + /// drag and drop operation. This API should also be used as the equivalent of 'on drag start' with + /// the [`Self::on_drag_move()`] API + /// The imperative API equivalent to [`InteractiveElement::on_drag()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_drag( &mut self, value: T, @@ -328,6 +457,11 @@ impl Interactivity { )); } + /// Bind the given callback on the hover start and end events of this element. Note that the boolean + /// passed to the callback is true when the hover starts and false when it ends. + /// The imperative API equivalent to [`InteractiveElement::on_drag()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut WindowContext) + 'static) where Self: Sized, @@ -339,6 +473,8 @@ impl Interactivity { self.hover_listener = Some(Box::new(listener)); } + /// Use the given callback to construct a new tooltip view when the mouse hovers over this element. + /// The imperative API equivalent to [`InteractiveElement::tooltip()`] pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) where Self: Sized, @@ -350,31 +486,43 @@ impl Interactivity { self.tooltip_builder = Some(Rc::new(build_tooltip)); } + /// Block the mouse from interacting with this element or any of it's children + /// The imperative API equivalent to [`InteractiveElement::block_mouse()`] pub fn block_mouse(&mut self) { self.block_mouse = true; } } +/// A trait for elements that want to use the standard GPUI event handlers that don't +/// require any state. pub trait InteractiveElement: Sized { + /// Retrieve the interactivity state associated with this element fn interactivity(&mut self) -> &mut Interactivity; + /// Assign this element to a group of elements that can be styled together fn group(mut self, group: impl Into) -> Self { self.interactivity().group = Some(group.into()); self } + /// Assign this elements fn id(mut self, id: impl Into) -> Stateful { self.interactivity().element_id = Some(id.into()); Stateful { element: self } } + /// Track the focus state of the given focus handle on this element. + /// If the focus handle is focused by the application, this element will + /// apply it's focused styles. fn track_focus(mut self, focus_handle: &FocusHandle) -> Focusable { self.interactivity().focusable = true; self.interactivity().tracked_focus_handle = Some(focus_handle.clone()); Focusable { element: self } } + /// Set the keymap context for this element. This will be used to determine + /// which action to dispatch from the keymap. fn key_context(mut self, key_context: C) -> Self where C: TryInto, @@ -386,6 +534,7 @@ pub trait InteractiveElement: Sized { self } + /// Apply the given style to this element when the mouse hovers over it fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self { debug_assert!( self.interactivity().hover_style.is_none(), @@ -395,6 +544,7 @@ pub trait InteractiveElement: Sized { self } + /// Apply the given style to this element when the mouse hovers over a group member fn group_hover( mut self, group_name: impl Into, @@ -407,6 +557,10 @@ pub trait InteractiveElement: Sized { self } + /// Bind the given callback to the mouse down event for the given mouse button, + /// the fluent API equivalent to [`Interactivity::on_mouse_down()`] + /// + /// See [`ViewContext::listener()`] to get access to the view state from this callback fn on_mouse_down( mut self, button: MouseButton, @@ -417,17 +571,27 @@ pub trait InteractiveElement: Sized { } #[cfg(any(test, feature = "test-support"))] + /// Set a key that can be used to look up this element's bounds + /// in the [`VisualTestContext::debug_bounds()`] map + /// This is a noop in release builds fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self { self.interactivity().debug_selector = Some(f()); self } #[cfg(not(any(test, feature = "test-support")))] + /// Set a key that can be used to look up this element's bounds + /// in the [`VisualTestContext::debug_bounds()`] map + /// This is a noop in release builds #[inline] fn debug_selector(self, _: impl FnOnce() -> String) -> Self { self } + /// Bind the given callback to the mouse down event for any button, during the capture phase + /// the fluent API equivalent to [`Interactivity::capture_any_mouse_down()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn capture_any_mouse_down( mut self, listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static, @@ -436,6 +600,10 @@ pub trait InteractiveElement: Sized { self } + /// Bind the given callback to the mouse down event for any button, during the capture phase + /// the fluent API equivalent to [`Interactivity::on_any_mouse_down()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_any_mouse_down( mut self, listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static, @@ -444,6 +612,10 @@ pub trait InteractiveElement: Sized { self } + /// Bind the given callback to the mouse up event for the given button, during the bubble phase + /// the fluent API equivalent to [`Interactivity::on_mouse_up()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_mouse_up( mut self, button: MouseButton, @@ -453,6 +625,10 @@ pub trait InteractiveElement: Sized { self } + /// Bind the given callback to the mouse up event for any button, during the capture phase + /// the fluent API equivalent to [`Interactivity::capture_any_mouse_up()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn capture_any_mouse_up( mut self, listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static, @@ -461,6 +637,11 @@ pub trait InteractiveElement: Sized { self } + /// Bind the given callback to the mouse down event, on any button, during the capture phase, + /// when the mouse is outside of the bounds of this element. + /// The fluent API equivalent to [`Interactivity::on_mouse_down_out()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_mouse_down_out( mut self, listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static, @@ -469,6 +650,11 @@ pub trait InteractiveElement: Sized { self } + /// Bind the given callback to the mouse up event, for the given button, during the capture phase, + /// when the mouse is outside of the bounds of this element. + /// The fluent API equivalent to [`Interactivity::on_mouse_up_out()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_mouse_up_out( mut self, button: MouseButton, @@ -478,6 +664,10 @@ pub trait InteractiveElement: Sized { self } + /// Bind the given callback to the mouse move event, during the bubble phase + /// The fluent API equivalent to [`Interactivity::on_mouse_move()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_mouse_move( mut self, listener: impl Fn(&MouseMoveEvent, &mut WindowContext) + 'static, @@ -486,6 +676,13 @@ pub trait InteractiveElement: Sized { self } + /// Bind the given callback to the mouse drag event of the given type. Note that this + /// will be called for all move events, inside or outside of this element, as long as the + /// drag was started with this element under the mouse. Useful for implementing draggable + /// UIs that don't conform to a drag and drop style interaction, like resizing. + /// The fluent API equivalent to [`Interactivity::on_drag_move()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_drag_move( mut self, listener: impl Fn(&DragMoveEvent, &mut WindowContext) + 'static, @@ -497,6 +694,10 @@ pub trait InteractiveElement: Sized { self } + /// Bind the given callback to scroll wheel events during the bubble phase + /// The fluent API equivalent to [`Interactivity::on_scroll_wheel()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_scroll_wheel( mut self, listener: impl Fn(&ScrollWheelEvent, &mut WindowContext) + 'static, @@ -506,6 +707,9 @@ pub trait InteractiveElement: Sized { } /// Capture the given action, before normal action dispatch can fire + /// The fluent API equivalent to [`Interactivity::on_scroll_wheel()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn capture_action( mut self, listener: impl Fn(&A, &mut WindowContext) + 'static, @@ -514,12 +718,21 @@ pub trait InteractiveElement: Sized { self } - /// Add a listener for the given action, fires during the bubble event phase + /// Bind the given callback to an action dispatch during the bubble phase + /// The fluent API equivalent to [`Interactivity::on_action()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_action(mut self, listener: impl Fn(&A, &mut WindowContext) + 'static) -> Self { self.interactivity().on_action(listener); self } + /// Bind the given callback to an action dispatch, based on a dynamic action parameter + /// instead of a type parameter. Useful for component libraries that want to expose + /// action bindings to their users. + /// The fluent API equivalent to [`Interactivity::on_boxed_action()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_boxed_action( mut self, action: &dyn Action, @@ -529,6 +742,10 @@ pub trait InteractiveElement: Sized { self } + /// Bind the given callback to key down events during the bubble phase + /// The fluent API equivalent to [`Interactivity::on_key_down()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_key_down( mut self, listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static, @@ -537,6 +754,10 @@ pub trait InteractiveElement: Sized { self } + /// Bind the given callback to key down events during the capture phase + /// The fluent API equivalent to [`Interactivity::capture_key_down()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn capture_key_down( mut self, listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static, @@ -545,11 +766,19 @@ pub trait InteractiveElement: Sized { self } + /// Bind the given callback to key up events during the bubble phase + /// The fluent API equivalent to [`Interactivity::on_key_up()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_key_up(mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) -> Self { self.interactivity().on_key_up(listener); self } + /// Bind the given callback to key up events during the capture phase + /// The fluent API equivalent to [`Interactivity::capture_key_up()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn capture_key_up( mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static, @@ -558,6 +787,7 @@ pub trait InteractiveElement: Sized { self } + /// Apply the given style when the given data type is dragged over this element fn drag_over(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self { self.interactivity() .drag_over_styles @@ -565,6 +795,7 @@ pub trait InteractiveElement: Sized { self } + /// Apply the given style when the given data type is dragged over this element's group fn group_drag_over( mut self, group_name: impl Into, @@ -580,11 +811,17 @@ pub trait InteractiveElement: Sized { self } + /// Bind the given callback to drop events of the given type, whether or not the drag started on this element + /// The fluent API equivalent to [`Interactivity::on_drop()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_drop(mut self, listener: impl Fn(&T, &mut WindowContext) + 'static) -> Self { self.interactivity().on_drop(listener); self } + /// Use the given predicate to determine whether or not a drop event should be dispatched to this element + /// The fluent API equivalent to [`Interactivity::can_drop()`] fn can_drop( mut self, predicate: impl Fn(&dyn Any, &mut WindowContext) -> bool + 'static, @@ -593,39 +830,49 @@ pub trait InteractiveElement: Sized { self } + /// Block the mouse from interacting with this element or any of it's children + /// The fluent API equivalent to [`Interactivity::block_mouse()`] fn block_mouse(mut self) -> Self { self.interactivity().block_mouse(); self } } +/// A trait for elements that want to use the standard GPUI interactivity features +/// that require state. pub trait StatefulInteractiveElement: InteractiveElement { + /// Set this element to focusable. fn focusable(mut self) -> Focusable { self.interactivity().focusable = true; Focusable { element: self } } + /// Set the overflow x and y to scroll. fn overflow_scroll(mut self) -> Self { self.interactivity().base_style.overflow.x = Some(Overflow::Scroll); self.interactivity().base_style.overflow.y = Some(Overflow::Scroll); self } + /// Set the overflow x to scroll. fn overflow_x_scroll(mut self) -> Self { self.interactivity().base_style.overflow.x = Some(Overflow::Scroll); self } + /// Set the overflow y to scroll. fn overflow_y_scroll(mut self) -> Self { self.interactivity().base_style.overflow.y = Some(Overflow::Scroll); self } + /// Track the scroll state of this element with the given handle. fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self { self.interactivity().scroll_handle = Some(scroll_handle.clone()); self } + /// Set the given styles to be applied when this element is active. fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self where Self: Sized, @@ -634,6 +881,7 @@ pub trait StatefulInteractiveElement: InteractiveElement { self } + /// Set the given styles to be applied when this element's group is active. fn group_active( mut self, group_name: impl Into, @@ -649,6 +897,10 @@ pub trait StatefulInteractiveElement: InteractiveElement { self } + /// Bind the given callback to click events of this element + /// The fluent API equivalent to [`Interactivity::on_click()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut WindowContext) + 'static) -> Self where Self: Sized, @@ -657,6 +909,12 @@ pub trait StatefulInteractiveElement: InteractiveElement { self } + /// On drag initiation, this callback will be used to create a new view to render the dragged value for a + /// drag and drop operation. This API should also be used as the equivalent of 'on drag start' with + /// the [`Self::on_drag_move()`] API + /// The fluent API equivalent to [`Interactivity::on_drag()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_drag( mut self, value: T, @@ -671,6 +929,11 @@ pub trait StatefulInteractiveElement: InteractiveElement { self } + /// Bind the given callback on the hover start and end events of this element. Note that the boolean + /// passed to the callback is true when the hover starts and false when it ends. + /// The fluent API equivalent to [`Interactivity::on_hover()`] + /// + /// See [`ViewContext::listener()`] to get access to a view's state from this callback fn on_hover(mut self, listener: impl Fn(&bool, &mut WindowContext) + 'static) -> Self where Self: Sized, @@ -679,6 +942,8 @@ pub trait StatefulInteractiveElement: InteractiveElement { self } + /// Use the given callback to construct a new tooltip view when the mouse hovers over this element. + /// The fluent API equivalent to [`Interactivity::tooltip()`] fn tooltip(mut self, build_tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) -> Self where Self: Sized, @@ -688,7 +953,9 @@ pub trait StatefulInteractiveElement: InteractiveElement { } } +/// A trait for providing focus related APIs to interactive elements pub trait FocusableElement: InteractiveElement { + /// Set the given styles to be applied when this element, specifically, is focused. fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self where Self: Sized, @@ -697,6 +964,7 @@ pub trait FocusableElement: InteractiveElement { self } + /// Set the given styles to be applied when this element is inside another element that is focused. fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self where Self: Sized, @@ -706,35 +974,36 @@ pub trait FocusableElement: InteractiveElement { } } -pub type MouseDownListener = +pub(crate) type MouseDownListener = Box; -pub type MouseUpListener = +pub(crate) type MouseUpListener = Box; -pub type MouseMoveListener = +pub(crate) type MouseMoveListener = Box; -pub type ScrollWheelListener = +pub(crate) type ScrollWheelListener = Box; -pub type ClickListener = Box; +pub(crate) type ClickListener = Box; -pub type DragListener = Box AnyView + 'static>; +pub(crate) type DragListener = Box AnyView + 'static>; type DropListener = Box; type CanDropPredicate = Box bool + 'static>; -pub type TooltipBuilder = Rc AnyView + 'static>; +pub(crate) type TooltipBuilder = Rc AnyView + 'static>; -pub type KeyDownListener = Box; +pub(crate) type KeyDownListener = + Box; -pub type KeyUpListener = Box; +pub(crate) type KeyUpListener = + Box; -pub type DragEventListener = Box; - -pub type ActionListener = Box; +pub(crate) type ActionListener = Box; +/// Construct a new [`Div`] element #[track_caller] pub fn div() -> Div { #[cfg(debug_assertions)] @@ -753,6 +1022,7 @@ pub fn div() -> Div { } } +/// A [`Div`] element, the all-in-one element for building complex UIs in GPUI pub struct Div { interactivity: Interactivity, children: SmallVec<[AnyElement; 2]>, @@ -771,8 +1041,8 @@ impl InteractiveElement for Div { } impl ParentElement for Div { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - &mut self.children + fn extend(&mut self, elements: impl IntoIterator) { + self.children.extend(elements) } } @@ -875,12 +1145,14 @@ impl IntoElement for Div { } } +/// The state a div needs to keep track of between frames. pub struct DivState { child_layout_ids: SmallVec<[LayoutId; 2]>, interactive_state: InteractiveElementState, } impl DivState { + /// Is the div currently being clicked on? pub fn is_active(&self) -> bool { self.interactive_state .pending_mouse_down @@ -889,56 +1161,67 @@ impl DivState { } } +/// The interactivity struct. Powers all of the general-purpose +/// interactivity in the `Div` element. #[derive(Default)] pub struct Interactivity { + /// The element ID of the element pub element_id: Option, - pub key_context: Option, - pub focusable: bool, - pub tracked_focus_handle: Option, - pub scroll_handle: Option, - pub group: Option, + pub(crate) key_context: Option, + pub(crate) focusable: bool, + pub(crate) tracked_focus_handle: Option, + pub(crate) scroll_handle: Option, + pub(crate) group: Option, + /// The base style of the element, before any modifications are applied + /// by focus, active, etc. pub base_style: Box, - pub focus_style: Option>, - pub in_focus_style: Option>, - pub hover_style: Option>, - pub group_hover_style: Option, - pub active_style: Option>, - pub group_active_style: Option, - pub drag_over_styles: Vec<(TypeId, StyleRefinement)>, - pub group_drag_over_styles: Vec<(TypeId, GroupStyle)>, - pub mouse_down_listeners: Vec, - pub mouse_up_listeners: Vec, - pub mouse_move_listeners: Vec, - pub scroll_wheel_listeners: Vec, - pub key_down_listeners: Vec, - pub key_up_listeners: Vec, - pub action_listeners: Vec<(TypeId, ActionListener)>, - pub drop_listeners: Vec<(TypeId, DropListener)>, - pub can_drop_predicate: Option, - pub click_listeners: Vec, - pub drag_listener: Option<(Box, DragListener)>, - pub hover_listener: Option>, - pub tooltip_builder: Option, - pub block_mouse: bool, + pub(crate) focus_style: Option>, + pub(crate) in_focus_style: Option>, + pub(crate) hover_style: Option>, + pub(crate) group_hover_style: Option, + pub(crate) active_style: Option>, + pub(crate) group_active_style: Option, + pub(crate) drag_over_styles: Vec<(TypeId, StyleRefinement)>, + pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>, + pub(crate) mouse_down_listeners: Vec, + pub(crate) mouse_up_listeners: Vec, + pub(crate) mouse_move_listeners: Vec, + pub(crate) scroll_wheel_listeners: Vec, + pub(crate) key_down_listeners: Vec, + pub(crate) key_up_listeners: Vec, + pub(crate) action_listeners: Vec<(TypeId, ActionListener)>, + pub(crate) drop_listeners: Vec<(TypeId, DropListener)>, + pub(crate) can_drop_predicate: Option, + pub(crate) click_listeners: Vec, + pub(crate) drag_listener: Option<(Box, DragListener)>, + pub(crate) hover_listener: Option>, + pub(crate) tooltip_builder: Option, + pub(crate) block_mouse: bool, #[cfg(debug_assertions)] - pub location: Option>, + pub(crate) location: Option>, #[cfg(any(test, feature = "test-support"))] - pub debug_selector: Option, + pub(crate) debug_selector: Option, } +/// The bounds and depth of an element in the computed element tree. #[derive(Clone, Debug)] pub struct InteractiveBounds { + /// The 2D bounds of the element pub bounds: Bounds, + /// The 'stacking order', or depth, for this element pub stacking_order: StackingOrder, } impl InteractiveBounds { + /// Checks whether this point was inside these bounds, and that these bounds where the topmost layer pub fn visibly_contains(&self, point: &Point, cx: &WindowContext) -> bool { self.bounds.contains(point) && cx.was_top_layer(point, &self.stacking_order) } + /// Checks whether this point was inside these bounds, and that these bounds where the topmost layer + /// under an active drag pub fn drag_target_contains(&self, point: &Point, cx: &WindowContext) -> bool { self.bounds.contains(point) && cx.was_top_layer_under_active_drag(point, &self.stacking_order) @@ -946,6 +1229,7 @@ impl InteractiveBounds { } impl Interactivity { + /// Layout this element according to this interactivity state's configured styles pub fn layout( &mut self, element_state: Option, @@ -984,6 +1268,14 @@ impl Interactivity { (layout_id, element_state) } + /// Paint this element according to this interactivity state's configured styles + /// and bind the element's mouse and keyboard events. + /// + /// content_size is the size of the content of the element, which may be larger than the + /// element's bounds if the element is scrollable. + /// + /// the final computed style will be passed to the provided function, along + /// with the current scroll offset pub fn paint( &mut self, bounds: Bounds, @@ -1600,6 +1892,7 @@ impl Interactivity { }); } + /// Compute the visual style for this element, based on the current bounds and the element's state. pub fn compute_style( &self, bounds: Option>, @@ -1707,16 +2000,19 @@ impl Interactivity { } } +/// The per-frame state of an interactive element. Used for tracking stateful interactions like clicks +/// and scroll offsets. #[derive(Default)] pub struct InteractiveElementState { - pub focus_handle: Option, - pub clicked_state: Option>>, - pub hover_state: Option>>, - pub pending_mouse_down: Option>>>, - pub scroll_offset: Option>>>, - pub active_tooltip: Option>>>, + pub(crate) focus_handle: Option, + pub(crate) clicked_state: Option>>, + pub(crate) hover_state: Option>>, + pub(crate) pending_mouse_down: Option>>>, + pub(crate) scroll_offset: Option>>>, + pub(crate) active_tooltip: Option>>>, } +/// The current active tooltip pub struct ActiveTooltip { pub(crate) tooltip: Option, pub(crate) _task: Option>, @@ -1725,7 +2021,10 @@ pub struct ActiveTooltip { /// Whether or not the element or a group that contains it is clicked by the mouse. #[derive(Copy, Clone, Default, Eq, PartialEq)] pub struct ElementClickedState { + /// True if this element's group has been clicked, false otherwise pub group: bool, + + /// True if this element has been clicked, false otherwise pub element: bool, } @@ -1736,7 +2035,7 @@ impl ElementClickedState { } #[derive(Default)] -pub struct GroupBounds(HashMap; 1]>>); +pub(crate) struct GroupBounds(HashMap; 1]>>); impl GroupBounds { pub fn get(name: &SharedString, cx: &mut AppContext) -> Option> { @@ -1760,7 +2059,9 @@ impl GroupBounds { } } +/// A wrapper around an element that can be focused. pub struct Focusable { + /// The element that is focusable pub element: E, } @@ -1824,11 +2125,12 @@ impl ParentElement for Focusable where E: ParentElement, { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - self.element.children_mut() + fn extend(&mut self, elements: impl Iterator) { + self.element.extend(elements) } } +/// A wrapper around an element that can store state, produced after assigning an ElementId. pub struct Stateful { element: E, } @@ -1898,14 +2200,13 @@ impl ParentElement for Stateful where E: ParentElement, { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - self.element.children_mut() + fn extend(&mut self, elements: impl Iterator) { + self.element.extend(elements) } } #[derive(Default)] struct ScrollHandleState { - // not great to have the nested rc's... offset: Rc>>, bounds: Bounds, child_bounds: Vec>, @@ -1913,6 +2214,9 @@ struct ScrollHandleState { overflow: Point, } +/// A handle to the scrollable aspects of an element. +/// Used for accessing scroll state, like the current scroll offset, +/// and for mutating the scroll state, like scrolling to a specific child. #[derive(Clone)] pub struct ScrollHandle(Rc>); @@ -1923,14 +2227,17 @@ impl Default for ScrollHandle { } impl ScrollHandle { + /// Construct a new scroll handle. pub fn new() -> Self { Self(Rc::default()) } + /// Get the current scroll offset. pub fn offset(&self) -> Point { *self.0.borrow().offset.borrow() } + /// Get the top child that's scrolled into view. pub fn top_item(&self) -> usize { let state = self.0.borrow(); let top = state.bounds.top() - state.offset.borrow().y; @@ -1949,11 +2256,12 @@ impl ScrollHandle { } } + /// Get the bounds for a specific child. pub fn bounds_for_item(&self, ix: usize) -> Option> { self.0.borrow().child_bounds.get(ix).cloned() } - /// scroll_to_item scrolls the minimal amount to ensure that the item is + /// scroll_to_item scrolls the minimal amount to ensure that the child is /// fully visible pub fn scroll_to_item(&self, ix: usize) { let state = self.0.borrow(); @@ -1981,6 +2289,7 @@ impl ScrollHandle { } } + /// Get the logical scroll top, based on a child index and a pixel offset. pub fn logical_scroll_top(&self) -> (usize, Pixels) { let ix = self.top_item(); let state = self.0.borrow(); @@ -1995,6 +2304,7 @@ impl ScrollHandle { } } + /// Set the logical scroll top, based on a child index and a pixel offset. pub fn set_logical_scroll_top(&self, ix: usize, px: Pixels) { self.0.borrow_mut().requested_scroll_top = Some((ix, px)); } diff --git a/crates/gpui/src/elements/overlay.rs b/crates/gpui/src/elements/overlay.rs index 6996a13cfaac61b84e9ba7df10f240710ca2d162..0ba90864e7e3d983b16e68161882d15f9562e771 100644 --- a/crates/gpui/src/elements/overlay.rs +++ b/crates/gpui/src/elements/overlay.rs @@ -60,8 +60,8 @@ impl Overlay { } impl ParentElement for Overlay { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - &mut self.children + fn extend(&mut self, elements: impl Iterator) { + self.children.extend(elements) } } diff --git a/crates/gpui/src/elements/text.rs b/crates/gpui/src/elements/text.rs index 8ab847bf6b6911499aca5457243ac1ec2f8690db..37736f7f93c8e373ad557d2a98cd8ec898ae475c 100644 --- a/crates/gpui/src/elements/text.rs +++ b/crates/gpui/src/elements/text.rs @@ -489,7 +489,7 @@ impl Element for InteractiveText { move |mut cx| async move { cx.background_executor().timer(TOOLTIP_DELAY).await; - cx.update(|_, cx| { + cx.update(|cx| { let new_tooltip = tooltip_builder(position, cx).map(|tooltip| ActiveTooltip { tooltip: Some(AnyTooltip { diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs index feb0e2e55141b6c152122034b040f70c7ef717ae..f7ddd232ecf02eeee3c25e231f70dc6af01b85e5 100644 --- a/crates/gpui/src/platform.rs +++ b/crates/gpui/src/platform.rs @@ -1,5 +1,3 @@ -#![deny(missing_docs)] - mod app_menu; mod keystroke; #[cfg(target_os = "macos")] diff --git a/crates/gpui/src/view.rs b/crates/gpui/src/view.rs index c5d759c61599a6082f5fa2531471ea4a9da34e4c..b6f6de7b6a5ccb0c43d40347b04b494a817b88f1 100644 --- a/crates/gpui/src/view.rs +++ b/crates/gpui/src/view.rs @@ -1,5 +1,3 @@ -#![deny(missing_docs)] - use crate::{ seal::Sealed, AnyElement, AnyModel, AnyWeakModel, AppContext, AvailableSpace, BorrowWindow, Bounds, ContentMask, Element, ElementId, Entity, EntityId, Flatten, FocusHandle, FocusableView, diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index 1a7a35bf57f23322c103bff9a0ed245687087d72..9697d162aee3dc0e97f2dc5320653dcbc0fddb0f 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -1,5 +1,3 @@ -#![deny(missing_docs)] - use crate::{ px, size, transparent_black, Action, AnyDrag, AnyTooltip, AnyView, AppContext, Arena, AsyncWindowContext, AvailableSpace, Bounds, BoxShadow, Context, Corners, CursorStyle, diff --git a/crates/story/src/story.rs b/crates/story/src/story.rs index 47bdab7f239643ae9e6fd2ebf2366c80ed8555f4..ff7b2bed86b7a7a397692a5dfc554c569f7a774b 100644 --- a/crates/story/src/story.rs +++ b/crates/story/src/story.rs @@ -67,8 +67,8 @@ impl StoryContainer { } impl ParentElement for StoryContainer { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - &mut self.children + fn extend(&mut self, elements: impl Iterator) { + self.children.extend(elements) } } @@ -372,7 +372,7 @@ impl RenderOnce for StorySection { } impl ParentElement for StorySection { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - &mut self.children + fn extend(&mut self, elements: impl Iterator) { + self.children.extend(elements) } } diff --git a/crates/ui/src/components/button/button_like.rs b/crates/ui/src/components/button/button_like.rs index aafb33cd6f541a7573f7910fc559a8d170416689..80dd7b5ce71a8e2632afc6a2f58b33d26ed59ca6 100644 --- a/crates/ui/src/components/button/button_like.rs +++ b/crates/ui/src/components/button/button_like.rs @@ -407,8 +407,8 @@ impl VisibleOnHover for ButtonLike { } impl ParentElement for ButtonLike { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - &mut self.children + fn extend(&mut self, elements: impl Iterator) { + self.children.extend(elements) } } diff --git a/crates/ui/src/components/label/label_like.rs b/crates/ui/src/components/label/label_like.rs index 6da07d81a39c8a51355b6d922e19c302c1c683ad..cddd849b89d7d15e6ebfa6367ad5829bfe4a709a 100644 --- a/crates/ui/src/components/label/label_like.rs +++ b/crates/ui/src/components/label/label_like.rs @@ -78,8 +78,8 @@ impl LabelCommon for LabelLike { } impl ParentElement for LabelLike { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - &mut self.children + fn extend(&mut self, elements: impl Iterator) { + self.children.extend(elements) } } diff --git a/crates/ui/src/components/list/list.rs b/crates/ui/src/components/list/list.rs index 436f3e034d17a757e9598fff0584d7239d6f4d65..9d102d709138b6271988663acc08a9a1a86dc392 100644 --- a/crates/ui/src/components/list/list.rs +++ b/crates/ui/src/components/list/list.rs @@ -40,8 +40,8 @@ impl List { } impl ParentElement for List { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - &mut self.children + fn extend(&mut self, elements: impl Iterator) { + self.children.extend(elements) } } diff --git a/crates/ui/src/components/list/list_item.rs b/crates/ui/src/components/list/list_item.rs index 33676ee11d1c27c5f36ca1faeb02c2eb6cfa3cb1..f23de39253e510c9b064af9bc081d7f0fd463c67 100644 --- a/crates/ui/src/components/list/list_item.rs +++ b/crates/ui/src/components/list/list_item.rs @@ -141,8 +141,8 @@ impl Selectable for ListItem { } impl ParentElement for ListItem { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - &mut self.children + fn extend(&mut self, elements: impl Iterator) { + self.children.extend(elements) } } diff --git a/crates/ui/src/components/popover.rs b/crates/ui/src/components/popover.rs index 3ef692e8624405a0daa7dd7a9a97becf7361b6ee..fea2a550fa92acd3d6a0cd5908a54de63066eed9 100644 --- a/crates/ui/src/components/popover.rs +++ b/crates/ui/src/components/popover.rs @@ -74,7 +74,7 @@ impl Popover { } impl ParentElement for Popover { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - &mut self.children + fn extend(&mut self, elements: impl Iterator) { + self.children.extend(elements) } } diff --git a/crates/ui/src/components/tab.rs b/crates/ui/src/components/tab.rs index 7f1fcca721b9524b8879f2c6051e7481dc8db6ab..db81bb5801609d46fc8cb8e0af2d5404acce54a3 100644 --- a/crates/ui/src/components/tab.rs +++ b/crates/ui/src/components/tab.rs @@ -92,8 +92,8 @@ impl Selectable for Tab { } impl ParentElement for Tab { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - &mut self.children + fn extend(&mut self, elements: impl Iterator) { + self.children.extend(elements) } } diff --git a/crates/ui/src/components/tab_bar.rs b/crates/ui/src/components/tab_bar.rs index 4b61d90bcdffc573d9c8940d5173e051f09b812e..abfd7284f2b4987c1d38ef235a338fa22a059cf0 100644 --- a/crates/ui/src/components/tab_bar.rs +++ b/crates/ui/src/components/tab_bar.rs @@ -83,8 +83,8 @@ impl TabBar { } impl ParentElement for TabBar { - fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> { - &mut self.children + fn extend(&mut self, elements: impl Iterator) { + self.children.extend(elements) } } diff --git a/crates/workspace/src/pane_group.rs b/crates/workspace/src/pane_group.rs index 476592f3745568e67fcbea9b44060cceea90370c..64e09e67cb15f9f6620af2921426ea63c6d39f81 100644 --- a/crates/workspace/src/pane_group.rs +++ b/crates/workspace/src/pane_group.rs @@ -904,8 +904,8 @@ mod element { } impl ParentElement for PaneAxisElement { - fn children_mut(&mut self) -> &mut smallvec::SmallVec<[AnyElement; 2]> { - &mut self.children + fn extend(&mut self, elements: impl Iterator) { + self.children.extend(elements) } }