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