Skip to main content

lumen_dioxus/charts/
interaction.rs

1//! The inspection state machine of interactive line charts, ported from lumen-core's
2//! `createLumenChartInteractionController` so keyboard and pointer inspection run in Rust on
3//! every renderer.
4
5use std::collections::HashMap;
6use std::sync::atomic::{AtomicUsize, Ordering};
7
8use dioxus::prelude::*;
9
10use super::model::ChartX;
11
12/// The cursor of a controlled interactive [`LineChart`](crate::LineChart).
13#[derive(Clone, Debug, PartialEq)]
14#[non_exhaustive]
15pub enum LineChartCursor {
16    /// No point is inspected.
17    Cleared,
18    /// The point with this x identity is inspected.
19    At(ChartX),
20}
21
22impl LineChartCursor {
23    /// The inspected x identity.
24    pub fn x(&self) -> Option<ChartX> {
25        match self {
26            Self::Cleared => None,
27            Self::At(x) => Some(x.clone()),
28        }
29    }
30}
31
32impl From<Option<ChartX>> for LineChartCursor {
33    fn from(value: Option<ChartX>) -> Self {
34        value.map_or(Self::Cleared, Self::At)
35    }
36}
37
38/// An inspection key.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub(crate) enum InspectionKey {
41    Previous,
42    Next,
43    First,
44    Last,
45    Escape,
46}
47
48impl InspectionKey {
49    pub(crate) fn from_key(key: &Key) -> Option<Self> {
50        match key {
51            Key::ArrowLeft => Some(Self::Previous),
52            Key::ArrowRight => Some(Self::Next),
53            Key::Home => Some(Self::First),
54            Key::End => Some(Self::Last),
55            Key::Escape => Some(Self::Escape),
56            _ => None,
57        }
58    }
59}
60
61/// A cursor change to report: the new x and whether it is announced to screen readers.
62#[derive(Clone, Debug, PartialEq)]
63pub(crate) struct CursorEmit {
64    pub(crate) x: Option<ChartX>,
65    pub(crate) announce: bool,
66}
67
68/// The pointer and keyboard flags of the inspection controller.
69#[derive(Clone, Debug, Default, PartialEq)]
70pub(crate) struct Inspection {
71    pub(crate) selected: Option<ChartX>,
72    pub(crate) pinned: bool,
73    pub(crate) dismissed: bool,
74    pub(crate) hovering: bool,
75}
76
77/// The index the inspection moves to for `key` (`Home`, `End`, or one step, clamped).
78pub(crate) fn next_index(
79    key: InspectionKey,
80    selected: Option<&ChartX>,
81    points: &[ChartX],
82) -> usize {
83    let last = points.len().saturating_sub(1);
84
85    match key {
86        InspectionKey::First | InspectionKey::Escape => 0,
87        InspectionKey::Last => last,
88        InspectionKey::Previous | InspectionKey::Next => {
89            let Some(index) = selected.and_then(|x| points.iter().position(|point| point == x))
90            else {
91                return 0;
92            };
93
94            if key == InspectionKey::Next {
95                (index + 1).min(last)
96            } else {
97                index.saturating_sub(1)
98            }
99        }
100    }
101}
102
103impl Inspection {
104    /// A key on the focused plot; `None` when the key is not handled.
105    pub(crate) fn key(&mut self, key: InspectionKey, points: &[ChartX]) -> Option<CursorEmit> {
106        if points.is_empty() {
107            return None;
108        }
109
110        if key == InspectionKey::Escape {
111            self.pinned = false;
112            self.dismissed = true;
113
114            return Some(CursorEmit {
115                x: None,
116                announce: true,
117            });
118        }
119
120        self.pinned = true;
121        self.dismissed = false;
122        self.hovering = false;
123        let index = next_index(key, self.selected.as_ref(), points);
124
125        Some(CursorEmit {
126            x: points.get(index).cloned(),
127            announce: true,
128        })
129    }
130
131    /// A pointer move over the plot, resolved to its closest point.
132    pub(crate) fn pointer_move(
133        &mut self,
134        closest: Option<ChartX>,
135        touch: bool,
136    ) -> Option<CursorEmit> {
137        if touch || self.pinned || self.dismissed {
138            return None;
139        }
140
141        self.hovering = true;
142
143        (closest != self.selected).then_some(CursorEmit {
144            x: closest,
145            announce: false,
146        })
147    }
148
149    /// A primary pointer press, which pins the closest point.
150    pub(crate) fn pointer_down(&mut self, closest: Option<ChartX>) -> CursorEmit {
151        self.pinned = true;
152        self.dismissed = false;
153        self.hovering = false;
154
155        CursorEmit {
156            x: closest,
157            announce: true,
158        }
159    }
160
161    /// The pointer left the chart: a hover inspection clears; a pinned one stays.
162    pub(crate) fn pointer_leave(&mut self) -> Option<CursorEmit> {
163        self.dismissed = false;
164        let emit = (self.hovering && !self.pinned).then_some(CursorEmit {
165            x: None,
166            announce: false,
167        });
168        self.hovering = false;
169        emit
170    }
171
172    /// A synchronized peer chart moved its cursor.
173    pub(crate) fn peer_select(&mut self, x: Option<ChartX>) {
174        self.hovering = false;
175        self.pinned = false;
176        self.dismissed = false;
177        self.selected = x;
178    }
179}
180
181/// The point whose position is closest to `position` (the first one on ties).
182pub(crate) fn closest_point(position: f64, points: &[(ChartX, f64)]) -> Option<ChartX> {
183    let mut distance = f64::INFINITY;
184    let mut result = None;
185
186    for (x, candidate) in points {
187        let difference = (candidate - position).abs();
188
189        if difference < distance {
190            result = Some(x.clone());
191            distance = difference;
192        }
193    }
194
195    result
196}
197
198/// Maps a client x coordinate into the `viewBox` of an SVG drawn with
199/// `preserveAspectRatio="xMidYMid meet"` inside `rect` (left, top, width, height).
200pub(crate) fn svg_x(
201    client_x: f64,
202    rect: (f64, f64, f64, f64),
203    view_box: (f64, f64),
204) -> Option<f64> {
205    let (left, _, width, height) = rect;
206    let (view_width, view_height) = view_box;
207
208    if width <= 0.0 || height <= 0.0 || view_width <= 0.0 || view_height <= 0.0 {
209        return None;
210    }
211
212    let scale = (width / view_width).min(height / view_height);
213    let offset = left + (width - view_width * scale) / 2.0;
214
215    Some((client_x - offset) / scale)
216}
217
218/// The inspection panel position, like lumen-core's `positionInspection`: beside the point,
219/// flipped left near the right edge, and kept 12px inside the chart frame.
220pub(crate) fn panel_position(
221    frame: (f64, f64, f64),
222    svg: (f64, f64, f64),
223    view_width: f64,
224    panel_width: f64,
225    position: f64,
226) -> Option<(f64, f64)> {
227    let (frame_left, frame_top, frame_width) = frame;
228    let (svg_left, svg_top, svg_width) = svg;
229
230    if view_width <= 0.0 {
231        return None;
232    }
233
234    let x = svg_left - frame_left + position / view_width * svg_width;
235    let left = if x + panel_width + 24.0 > frame_width {
236        x - panel_width - 16.0
237    } else {
238        x + 16.0
239    };
240
241    Some((
242        12f64.max((frame_width - panel_width - 12.0).min(left)),
243        svg_top - frame_top + 12.0,
244    ))
245}
246
247/// One synchronized cursor move: which chart moved, where, and a sequence number.
248#[derive(Clone, Debug, PartialEq)]
249pub(crate) struct SyncMove {
250    pub(crate) origin: usize,
251    pub(crate) x: Option<ChartX>,
252    pub(crate) sequence: u64,
253}
254
255/// The latest cursor move of every sync group in the app.
256pub(crate) static CHART_SYNC: GlobalSignal<HashMap<String, SyncMove>> =
257    Signal::global(HashMap::new);
258
259static NEXT_CHART: AtomicUsize = AtomicUsize::new(0);
260
261/// A stable identity for a chart instance, used to ignore its own sync moves.
262pub(crate) fn use_chart_instance() -> usize {
263    use_hook(|| NEXT_CHART.fetch_add(1, Ordering::Relaxed))
264}
265
266/// Publishes a cursor move to the other charts of `group`.
267pub(crate) fn publish_sync(group: &str, origin: usize, x: Option<ChartX>) {
268    let mut sync = CHART_SYNC.signal();
269    let mut groups = sync.write();
270    let sequence = groups.get(group).map_or(0, |entry| entry.sequence + 1);
271
272    groups.insert(
273        group.to_string(),
274        SyncMove {
275            origin,
276            x,
277            sequence,
278        },
279    );
280}
281
282#[cfg(test)]
283mod tests {
284    use super::{Inspection, InspectionKey, closest_point, next_index, panel_position, svg_x};
285    use crate::charts::model::ChartX;
286
287    fn points() -> Vec<ChartX> {
288        vec![ChartX::from("a"), ChartX::from("b"), ChartX::from("c")]
289    }
290
291    #[test]
292    fn keys_clamp_to_the_first_and_last_points() {
293        let points = points();
294        assert_eq!(next_index(InspectionKey::Next, None, &points), 0);
295        assert_eq!(
296            next_index(InspectionKey::Next, Some(&points[0]), &points),
297            1
298        );
299        assert_eq!(
300            next_index(InspectionKey::Next, Some(&points[2]), &points),
301            2
302        );
303        assert_eq!(
304            next_index(InspectionKey::Previous, Some(&points[0]), &points),
305            0
306        );
307        assert_eq!(
308            next_index(InspectionKey::Previous, Some(&points[2]), &points),
309            1
310        );
311        assert_eq!(next_index(InspectionKey::Last, None, &points), 2);
312        assert_eq!(
313            next_index(InspectionKey::First, Some(&points[2]), &points),
314            0
315        );
316        assert_eq!(
317            next_index(InspectionKey::Previous, Some(&ChartX::from("z")), &points),
318            0
319        );
320        assert_eq!(next_index(InspectionKey::Last, None, &[]), 0);
321    }
322
323    #[test]
324    fn keyboard_pins_and_escape_dismisses() {
325        let points = points();
326        let mut state = Inspection::default();
327        let emit = state.key(InspectionKey::Last, &points).unwrap();
328        assert_eq!(emit.x, Some(ChartX::from("c")));
329        assert!(emit.announce && state.pinned);
330        state.selected = emit.x;
331        assert!(state.pointer_move(Some(ChartX::from("a")), false).is_none());
332        let escape = state.key(InspectionKey::Escape, &points).unwrap();
333        assert_eq!(escape.x, None);
334        assert!(state.dismissed && !state.pinned);
335        assert!(state.key(InspectionKey::Next, &[]).is_none());
336    }
337
338    #[test]
339    fn hover_follows_the_pointer_until_it_leaves() {
340        let mut state = Inspection::default();
341        assert!(state.pointer_move(Some(ChartX::from("a")), true).is_none());
342        let hover = state.pointer_move(Some(ChartX::from("a")), false).unwrap();
343        assert!(!hover.announce);
344        state.selected = hover.x;
345        assert!(state.pointer_move(Some(ChartX::from("a")), false).is_none());
346        let leave = state.pointer_leave().unwrap();
347        assert_eq!(leave.x, None);
348        assert!(state.pointer_leave().is_none());
349        let pinned = state.pointer_down(Some(ChartX::from("b")));
350        assert!(pinned.announce && state.pinned);
351        assert!(state.pointer_leave().is_none());
352        state.peer_select(Some(ChartX::from("c")));
353        assert!(!state.pinned && state.selected == Some(ChartX::from("c")));
354    }
355
356    #[test]
357    fn pointer_geometry_maps_into_the_view_box() {
358        let points = vec![(ChartX::from("a"), 10.0), (ChartX::from("b"), 50.0)];
359        assert_eq!(closest_point(28.0, &points), Some(ChartX::from("a")));
360        assert_eq!(closest_point(31.0, &points), Some(ChartX::from("b")));
361        assert_eq!(closest_point(31.0, &[]), None);
362        assert_eq!(
363            svg_x(150.0, (100.0, 0.0, 320.0, 120.0), (640.0, 240.0)),
364            Some(100.0)
365        );
366        assert_eq!(svg_x(150.0, (100.0, 0.0, 0.0, 120.0), (640.0, 240.0)), None);
367        assert_eq!(
368            panel_position((0.0, 0.0, 600.0), (20.0, 40.0, 560.0), 640.0, 200.0, 320.0),
369            Some((316.0, 52.0))
370        );
371        assert_eq!(
372            panel_position((0.0, 0.0, 600.0), (20.0, 40.0, 560.0), 640.0, 200.0, 600.0),
373            Some((329.0, 52.0))
374        );
375    }
376}