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