Skip to main content

gpui_base/plot/
mod.rs

1//! Unstyled plotting: scales, shapes, axes, grids, labels, and the element and
2//! hover tracking behind every [`Plot`].
3//!
4//! Colors are always handed in by the caller. A styled layer supplies chart
5//! defaults, the tooltip overlay, and hover and appear timing through
6//! [`PlotMotion`].
7mod appear;
8mod axis;
9mod element;
10mod grid;
11mod hover;
12pub mod label;
13mod path_cache;
14pub mod scale;
15pub mod shape;
16
17use std::{fmt::Debug, ops::Add, time::Duration};
18
19use gpui::{
20    AnyElement, App, Bounds, ElementId, IntoElement, Path, PathBuilder, Pixels, Point,
21    SharedString, Window, point, px,
22};
23
24use crate::{Spring, motion::Transition};
25
26pub use appear::{PlotAppear, PlotAppearScope};
27#[allow(deprecated)]
28pub use axis::AXIS_GAP;
29pub use axis::{AxisLabelPlacement, AxisLabelSide, AxisText, PlotAxis, axis_gutter};
30pub use element::PlotElement;
31pub use grid::Grid;
32pub use hover::{PlotHover, TooltipState, hover_progress, is_hover_entering, pointer_spring};
33pub use label::PlotLabel;
34pub use path_cache::{PathCache, PathCaches, ShapeKey};
35pub use scale::PlotValue;
36
37/// The timing of a plot's motion: how its data marks appear when it is first
38/// painted, how its hover progress fades in and out, and the spring a pointer
39/// follows the hovered datum with.
40///
41/// Base installs no motion of its own: every duration defaults to zero, so the
42/// hover appears, fades and glides at once. Product timing belongs to the
43/// styled layer, which projects it through [`crate::PlotTheme`].
44#[derive(Clone)]
45pub struct PlotMotion {
46    pointer: Spring,
47    enter: Transition,
48    exit: Transition,
49    appear: Transition,
50}
51
52impl Default for PlotMotion {
53    fn default() -> Self {
54        Self {
55            pointer: Spring::new(Duration::ZERO),
56            enter: Transition::new(Duration::ZERO),
57            exit: Transition::new(Duration::ZERO),
58            appear: Transition::new(Duration::ZERO),
59        }
60    }
61}
62
63impl PlotMotion {
64    /// The spring a crosshair, highlight band or hover dot follows the hovered
65    /// datum with.
66    pub fn with_pointer(mut self, pointer: Spring) -> Self {
67        self.pointer = pointer;
68        self
69    }
70
71    /// How the hover fades in when the cursor lands on a datum.
72    pub fn with_enter(mut self, enter: Transition) -> Self {
73        self.enter = enter;
74        self
75    }
76
77    /// How the hover fades out after the cursor leaves.
78    pub fn with_exit(mut self, exit: Transition) -> Self {
79        self.exit = exit;
80        self
81    }
82
83    /// How a plot's data marks appear the first time it is painted; see
84    /// [`PlotAppear`].
85    pub fn with_appear(mut self, appear: Transition) -> Self {
86        self.appear = appear;
87        self
88    }
89
90    pub fn pointer(&self) -> Spring {
91        self.pointer
92    }
93
94    pub fn enter(&self) -> &Transition {
95        &self.enter
96    }
97
98    pub fn exit(&self) -> &Transition {
99        &self.exit
100    }
101
102    pub fn appear(&self) -> &Transition {
103        &self.appear
104    }
105}
106
107pub trait Plot: IntoElement {
108    /// Lay out and place the child elements this plot hosts (e.g. element labels).
109    ///
110    /// Called during the element's prepaint phase, so implementations may use
111    /// [`AnyElement::layout_as_root`] / [`AnyElement::prepaint_at`] to measure and
112    /// position children — neither is legal from [`Plot::paint`]. The returned
113    /// elements are painted right after `paint`, below the tooltip overlay.
114    ///
115    /// Runs before [`Plot::tooltip_state`] and [`Plot::tooltip`], so anything
116    /// resolved here can be reused by them.
117    ///
118    /// The default returns no children.
119    fn prepaint(
120        &mut self,
121        _bounds: Bounds<Pixels>,
122        _window: &mut Window,
123        _cx: &mut App,
124    ) -> Vec<AnyElement> {
125        vec![]
126    }
127
128    fn paint(&mut self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App);
129
130    /// A stable element id that keeps this plot's state across frames.
131    ///
132    /// Return `Some(id)` to opt in to appear motion and, unless
133    /// [`Plot::interactive`] says otherwise, tooltips and hover motion; the id
134    /// must be unique among sibling elements. Returning `None` (the default for
135    /// a hand-written plot) leaves the plot a pure element that neither appears
136    /// nor tracks hover.
137    ///
138    /// The charts in GPUI Component always return `Some`: their id defaults to the
139    /// source location they were constructed at, and `id` renames it.
140    fn id(&self) -> Option<ElementId> {
141        None
142    }
143
144    /// The name assistive technology reads for this plot.
145    ///
146    /// A plot paints its marks directly and has no text of its own, so it is
147    /// left out of the accessibility tree unless it returns `Some`. Then it is
148    /// an image node named by the label, which needs an [`Plot::id`] too.
149    ///
150    /// The default returns `None`.
151    fn accessibility_label(&self) -> Option<SharedString> {
152        None
153    }
154
155    /// Whether a plot with an [`Plot::id`] tracks hover and shows its tooltip.
156    ///
157    /// `false` keeps the id's state — appear motion and path caches — without
158    /// the hitbox, hover tracking or overlay. The default is `true`, so a plot
159    /// opts in to tooltips by returning an id.
160    fn interactive(&self) -> bool {
161        true
162    }
163
164    /// Receive how far the plot's data marks have appeared this frame, before
165    /// [`Plot::hover`] and [`Plot::paint`] run.
166    ///
167    /// Called on every frame the plot has an [`Plot::id`]; see [`PlotAppear`].
168    /// Without an [`Plot::appear_generation`] the appear is always complete.
169    /// The default ignores it.
170    fn appear(&mut self, _appear: PlotAppear, _window: &mut Window, _cx: &mut App) {}
171
172    /// Opt in to appear motion: `Some` draws the plot in the first time its
173    /// id is painted, and again whenever the value changes, such as when a
174    /// chart switches to another symbol or period.
175    ///
176    /// The default, `None`, tracks no appear, keeps no state for it and asks
177    /// for no frames, so a plot that does not draw in costs nothing.
178    fn appear_generation(&self) -> Option<u64> {
179        None
180    }
181
182    /// Map the cursor to the tooltip state to display.
183    ///
184    /// `position` is the cursor position relative to the plot's top-left origin (already
185    /// origin-subtracted), and `bounds` is the painted area. Return the [`TooltipState`]
186    /// to display (highlighted index, crosshair point, dots), or `None` to show
187    /// nothing. Only called while the cursor is inside `bounds`.
188    ///
189    /// The default returns `None`.
190    fn tooltip_state(
191        &self,
192        _position: Point<Pixels>,
193        _bounds: Bounds<Pixels>,
194        _cx: &App,
195    ) -> Option<TooltipState> {
196        None
197    }
198
199    /// Receive the hovered datum this frame, before [`Plot::tooltip`] and
200    /// [`Plot::paint`] run.
201    ///
202    /// `hover` carries the [`TooltipState`] the cursor resolved to, and it
203    /// lingers after the cursor leaves while [`PlotHover::progress`] eases back to
204    /// zero, so a hover-driven presentation can fade out over the last datum
205    /// instead of vanishing. `None` means nothing is hovered and nothing is
206    /// fading.
207    ///
208    /// Called on every frame the plot has an [`Plot::id`], so this is where a
209    /// plot samples its hover motion ([`crate::motion::transition`],
210    /// [`PlotHover::glide`]) and keeps the result for the other two methods.
211    /// The default ignores the hover.
212    fn hover(&mut self, _hover: Option<&PlotHover>, _window: &mut Window, _cx: &mut App) {}
213
214    /// Render the tooltip overlay for the active [`TooltipState`].
215    ///
216    /// `cursor` is the live cursor position (relative to the plot origin) and `bounds` is the
217    /// plot's painted area, so the tooltip box can follow the cursor (pass `cursor` and
218    /// `bounds.size` to the styled layer's tooltip). Return the overlay element; it is
219    /// painted absolutely positioned above the plot graphics but below sibling content
220    /// drawn after the plot (a box that may overflow the plot should `deferred` itself).
221    /// The default returns `None`.
222    ///
223    /// Also called while the hover fades out, with the lingering `state` and the
224    /// last `cursor`; the overlay renders within the plot's element scope, so it can
225    /// fade with [`hover_progress`].
226    fn tooltip(
227        &self,
228        _state: &TooltipState,
229        _cursor: Point<Pixels>,
230        _bounds: Bounds<Pixels>,
231        _window: &mut Window,
232        _cx: &mut App,
233    ) -> Option<AnyElement> {
234        None
235    }
236}
237
238/// How a [`Line`](shape::Line) or [`Area`](shape::Area) connects its points,
239/// like d3's curve factories.
240#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
241pub enum Curve {
242    /// A smooth curve through every point (`d3.curveNatural`).
243    #[default]
244    Natural,
245    /// Straight segments between points (`d3.curveLinear`).
246    Linear,
247    /// A step that holds each value until the next point (`d3.curveStepAfter`).
248    StepAfter,
249}
250
251pub fn origin_point<T>(x: T, y: T, origin: Point<T>) -> Point<T>
252where
253    T: Default + Clone + Debug + PartialEq + Add<Output = T>,
254{
255    point(x, y) + origin
256}
257
258pub fn polygon<T>(points: &[Point<T>], bounds: &Bounds<Pixels>) -> Option<Path>
259where
260    T: Default + Clone + Copy + Debug + Into<f32> + PartialEq,
261{
262    let mut path = PathBuilder::stroke(px(1.));
263    let points = &points
264        .iter()
265        .map(|p| {
266            point(
267                px(p.x.into() + bounds.origin.x.as_f32()),
268                px(p.y.into() + bounds.origin.y.as_f32()),
269            )
270        })
271        .collect::<Vec<_>>();
272    path.add_polygon(points, false);
273    path.build().ok()
274}