Skip to main content

gpui_base/plot/
element.rs

1//! The element behind every [`Plot`]: layout, appear and hover tracking and
2//! the overlay the plot returns from [`Plot::tooltip`].
3use std::{cell::Cell, rc::Rc};
4
5use gpui::{
6    AnyElement, App, Bounds, Element, ElementId, GlobalElementId, Hitbox, HitboxBehavior,
7    InspectorElementId, LayoutId, LongPressEvent, MouseMoveEvent, Pixels, Point, Size, Style,
8    TouchPhase, Window,
9};
10
11use super::{Plot, PlotAppear, appear::track_appear, hover::track_hover};
12
13/// Paints a [`Plot`] filling its container, with appear tracking when the plot
14/// has an [`Plot::id`], and hover tracking and the plot's tooltip overlay when
15/// it is also [`Plot::interactive`].
16///
17/// A plot becomes an element through this type:
18///
19/// ```ignore
20/// impl IntoElement for Sparkline {
21///     type Element = PlotElement<Self>;
22///
23///     fn into_element(self) -> Self::Element {
24///         PlotElement::new(self)
25///     }
26/// }
27/// ```
28///
29/// GPUI Component's `#[derive(IntoPlot)]` writes that impl.
30pub struct PlotElement<P>(P);
31
32impl<P: Plot + 'static> PlotElement<P> {
33    pub fn new(plot: P) -> Self {
34        Self(plot)
35    }
36
37    /// The last cursor position (plot-relative), shared by `prepaint` and `paint`.
38    fn tooltip_cursor(
39        global_id: &GlobalElementId,
40        window: &mut Window,
41    ) -> Rc<Cell<Option<Point<Pixels>>>> {
42        window.with_element_state(global_id, |prev, _| {
43            let cell: Rc<Cell<Option<Point<Pixels>>>> = prev.unwrap_or_default();
44            (cell.clone(), cell)
45        })
46    }
47}
48
49impl<P: Plot + 'static> Element for PlotElement<P> {
50    type RequestLayoutState = ();
51    // The occlusion-aware hitbox, the plot's prepainted children and the
52    // prepainted tooltip overlay, carried from `prepaint` to `paint`.
53    type PrepaintState = (Option<Hitbox>, Vec<AnyElement>, Option<AnyElement>);
54
55    fn id(&self) -> Option<ElementId> {
56        // `Some` gives the plot element state: appear motion and, when
57        // interactive, tooltips.
58        self.0.id()
59    }
60
61    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
62        None
63    }
64
65    fn request_layout(
66        &mut self,
67        _: Option<&GlobalElementId>,
68        _: Option<&InspectorElementId>,
69        window: &mut Window,
70        cx: &mut App,
71    ) -> (LayoutId, Self::RequestLayoutState) {
72        let style = Style {
73            size: Size::full(),
74            ..Default::default()
75        };
76        (window.request_layout(style, None, cx), ())
77    }
78
79    fn prepaint(
80        &mut self,
81        global_id: Option<&GlobalElementId>,
82        _: Option<&InspectorElementId>,
83        bounds: Bounds<Pixels>,
84        _: &mut Self::RequestLayoutState,
85        window: &mut Window,
86        cx: &mut App,
87    ) -> Self::PrepaintState {
88        // Children are laid out here, where `layout_as_root` / `prepaint_at` are legal,
89        // and before the early return so plots without an id still get them.
90        let children = self.0.prepaint(bounds, window, cx);
91
92        let Some(global_id) = global_id else {
93            return (None, children, None);
94        };
95
96        let appear = match self.0.appear_generation() {
97            Some(generation) => track_appear(global_id, generation, window, cx),
98            None => PlotAppear::complete(),
99        };
100        let appearing = appear.is_appearing();
101        self.0.appear(appear, window, cx);
102
103        if !self.0.interactive() {
104            return (None, children, None);
105        }
106
107        // `Hitbox::is_hovered` is false while an open popup or modal covers the plot.
108        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
109
110        // The cell only gates visibility; the position comes from the live mouse and
111        // this frame's bounds so the tooltip does not lag a frame while scrolling.
112        let cursor = Self::tooltip_cursor(global_id, window)
113            .get()
114            .map(|_| window.mouse_position())
115            .filter(|mouse| bounds.contains(mouse))
116            .map(|mouse| mouse - bounds.origin);
117        // No tooltip while the marks draw in: its dots would land on data not
118        // painted yet.
119        let live = cursor
120            .filter(|_| !appearing)
121            .and_then(|position| self.0.tooltip_state(position, bounds, cx));
122
123        // The datum under the cursor, or the last one while its hover fades out.
124        let hover = track_hover(live, cursor, window, cx);
125        self.0
126            .hover(hover.as_ref().map(|(hover, _)| hover), window, cx);
127
128        let overlay = hover.and_then(|(hover, cursor)| {
129            let mut overlay = self.0.tooltip(hover.state(), cursor, bounds, window, cx)?;
130            overlay.prepaint_as_root(bounds.origin, bounds.size.into(), window, cx);
131            Some(overlay)
132        });
133
134        (Some(hitbox), children, overlay)
135    }
136
137    fn paint(
138        &mut self,
139        global_id: Option<&GlobalElementId>,
140        _: Option<&InspectorElementId>,
141        bounds: Bounds<Pixels>,
142        _: &mut Self::RequestLayoutState,
143        prepaint: &mut Self::PrepaintState,
144        window: &mut Window,
145        cx: &mut App,
146    ) {
147        self.0.paint(bounds, window, cx);
148
149        let (hitbox, children, overlay) = prepaint;
150        for child in children.iter_mut() {
151            child.paint(window, cx);
152        }
153
154        if let (Some(global_id), Some(hitbox)) = (global_id, hitbox.as_ref()) {
155            let cell = Self::tooltip_cursor(global_id, window);
156            let hitbox = hitbox.clone();
157            // Notify only the view painting this plot: `window.refresh()` would drop
158            // every sibling view's cache on each pixel of mouse movement.
159            let view = window.current_view();
160
161            if cfg!(any(target_os = "ios", target_os = "android")) {
162                // A finger has no hover: only a long press opens the tooltip, drags
163                // the crosshair, and closes it on lift.
164                window.on_mouse_event(
165                    move |e: &LongPressEvent, phase, window: &mut Window, cx: &mut App| {
166                        if !phase.bubble() {
167                            return;
168                        }
169                        let next = match e.phase {
170                            TouchPhase::Started => {
171                                if window.default_prevented() || !hitbox.is_hovered(window) {
172                                    return;
173                                }
174                                window.prevent_default();
175                                Some(e.start_position - bounds.origin)
176                            }
177                            TouchPhase::Moved => {
178                                if cell.get().is_none() {
179                                    return;
180                                }
181                                Some(e.position - bounds.origin)
182                            }
183                            TouchPhase::Ended | TouchPhase::Cancelled => None,
184                        };
185                        if cell.get() != next {
186                            cell.set(next);
187                            cx.notify(view);
188                        }
189                    },
190                );
191            } else {
192                // Relayout can move the plot under a still cursor without a move
193                // event, so re-derive hover each frame; only a visibility flip needs
194                // a corrective frame.
195                let next = hitbox
196                    .is_hovered(window)
197                    .then(|| window.mouse_position() - bounds.origin);
198                if cell.get() != next {
199                    let visibility_changed = cell.get().is_some() != next.is_some();
200                    cell.set(next);
201                    if visibility_changed {
202                        window.request_animation_frame();
203                    }
204                }
205
206                window.on_mouse_event(
207                    move |e: &MouseMoveEvent, _, window: &mut Window, cx: &mut App| {
208                        let next = hitbox
209                            .is_hovered(window)
210                            .then(|| e.position - bounds.origin);
211                        if cell.get() != next {
212                            cell.set(next);
213                            cx.notify(view);
214                        }
215                    },
216                );
217            }
218        }
219
220        // Crosshair and dots paint above the plot; the deferred box paints above everything.
221        if let Some(overlay) = overlay.as_mut() {
222            overlay.paint(window, cx);
223        }
224    }
225}