lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! The inspection state machine of interactive line charts, ported from lumen-core's
//! `createLumenChartInteractionController` so keyboard and pointer inspection run in Rust on
//! every renderer.

use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};

use dioxus::prelude::*;

use super::model::ChartX;

/// The cursor of a controlled interactive [`LineChart`](crate::LineChart).
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum LineChartCursor {
    /// No point is inspected.
    Cleared,
    /// The point with this x identity is inspected.
    At(ChartX),
}

impl LineChartCursor {
    /// The inspected x identity.
    pub fn x(&self) -> Option<ChartX> {
        match self {
            Self::Cleared => None,
            Self::At(x) => Some(x.clone()),
        }
    }
}

impl From<Option<ChartX>> for LineChartCursor {
    fn from(value: Option<ChartX>) -> Self {
        value.map_or(Self::Cleared, Self::At)
    }
}

/// An inspection key.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum InspectionKey {
    Previous,
    Next,
    First,
    Last,
    Escape,
}

impl InspectionKey {
    pub(crate) fn from_key(key: &Key) -> Option<Self> {
        match key {
            Key::ArrowLeft => Some(Self::Previous),
            Key::ArrowRight => Some(Self::Next),
            Key::Home => Some(Self::First),
            Key::End => Some(Self::Last),
            Key::Escape => Some(Self::Escape),
            _ => None,
        }
    }
}

/// A cursor change to report: the new x and whether it is announced to screen readers.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct CursorEmit {
    pub(crate) x: Option<ChartX>,
    pub(crate) announce: bool,
}

/// The pointer and keyboard flags of the inspection controller.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Inspection {
    pub(crate) selected: Option<ChartX>,
    pub(crate) pinned: bool,
    pub(crate) dismissed: bool,
    pub(crate) hovering: bool,
}

/// The index the inspection moves to for `key` (`Home`, `End`, or one step, clamped).
pub(crate) fn next_index(
    key: InspectionKey,
    selected: Option<&ChartX>,
    points: &[ChartX],
) -> usize {
    let last = points.len().saturating_sub(1);

    match key {
        InspectionKey::First | InspectionKey::Escape => 0,
        InspectionKey::Last => last,
        InspectionKey::Previous | InspectionKey::Next => {
            let Some(index) = selected.and_then(|x| points.iter().position(|point| point == x))
            else {
                return 0;
            };

            if key == InspectionKey::Next {
                (index + 1).min(last)
            } else {
                index.saturating_sub(1)
            }
        }
    }
}

impl Inspection {
    /// A key on the focused plot; `None` when the key is not handled.
    pub(crate) fn key(&mut self, key: InspectionKey, points: &[ChartX]) -> Option<CursorEmit> {
        if points.is_empty() {
            return None;
        }

        if key == InspectionKey::Escape {
            self.pinned = false;
            self.dismissed = true;

            return Some(CursorEmit {
                x: None,
                announce: true,
            });
        }

        self.pinned = true;
        self.dismissed = false;
        self.hovering = false;
        let index = next_index(key, self.selected.as_ref(), points);

        Some(CursorEmit {
            x: points.get(index).cloned(),
            announce: true,
        })
    }

    /// A pointer move over the plot, resolved to its closest point.
    pub(crate) fn pointer_move(
        &mut self,
        closest: Option<ChartX>,
        touch: bool,
    ) -> Option<CursorEmit> {
        if touch || self.pinned || self.dismissed {
            return None;
        }

        self.hovering = true;

        (closest != self.selected).then_some(CursorEmit {
            x: closest,
            announce: false,
        })
    }

    /// A primary pointer press, which pins the closest point.
    pub(crate) fn pointer_down(&mut self, closest: Option<ChartX>) -> CursorEmit {
        self.pinned = true;
        self.dismissed = false;
        self.hovering = false;

        CursorEmit {
            x: closest,
            announce: true,
        }
    }

    /// The pointer left the chart: a hover inspection clears; a pinned one stays.
    pub(crate) fn pointer_leave(&mut self) -> Option<CursorEmit> {
        self.dismissed = false;
        let emit = (self.hovering && !self.pinned).then_some(CursorEmit {
            x: None,
            announce: false,
        });
        self.hovering = false;
        emit
    }

    /// A synchronized peer chart moved its cursor.
    pub(crate) fn peer_select(&mut self, x: Option<ChartX>) {
        self.hovering = false;
        self.pinned = false;
        self.dismissed = false;
        self.selected = x;
    }
}

/// The point whose position is closest to `position` (the first one on ties).
pub(crate) fn closest_point(position: f64, points: &[(ChartX, f64)]) -> Option<ChartX> {
    let mut distance = f64::INFINITY;
    let mut result = None;

    for (x, candidate) in points {
        let difference = (candidate - position).abs();

        if difference < distance {
            result = Some(x.clone());
            distance = difference;
        }
    }

    result
}

/// Maps a client x coordinate into the `viewBox` of an SVG drawn with
/// `preserveAspectRatio="xMidYMid meet"` inside `rect` (left, top, width, height).
pub(crate) fn svg_x(
    client_x: f64,
    rect: (f64, f64, f64, f64),
    view_box: (f64, f64),
) -> Option<f64> {
    let (left, _, width, height) = rect;
    let (view_width, view_height) = view_box;

    if width <= 0.0 || height <= 0.0 || view_width <= 0.0 || view_height <= 0.0 {
        return None;
    }

    let scale = (width / view_width).min(height / view_height);
    let offset = left + (width - view_width * scale) / 2.0;

    Some((client_x - offset) / scale)
}

/// The inspection panel position, like lumen-core's `positionInspection`: beside the point,
/// flipped left near the right edge, and kept 12px inside the chart frame.
pub(crate) fn panel_position(
    frame: (f64, f64, f64),
    svg: (f64, f64, f64),
    view_width: f64,
    panel_width: f64,
    position: f64,
) -> Option<(f64, f64)> {
    let (frame_left, frame_top, frame_width) = frame;
    let (svg_left, svg_top, svg_width) = svg;

    if view_width <= 0.0 {
        return None;
    }

    let x = svg_left - frame_left + position / view_width * svg_width;
    let left = if x + panel_width + 24.0 > frame_width {
        x - panel_width - 16.0
    } else {
        x + 16.0
    };

    Some((
        12f64.max((frame_width - panel_width - 12.0).min(left)),
        svg_top - frame_top + 12.0,
    ))
}

/// One synchronized cursor move: which chart moved, where, and a sequence number.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct SyncMove {
    pub(crate) origin: usize,
    pub(crate) x: Option<ChartX>,
    pub(crate) sequence: u64,
}

/// The latest cursor move of every sync group in the app.
pub(crate) static CHART_SYNC: GlobalSignal<HashMap<String, SyncMove>> =
    Signal::global(HashMap::new);

static NEXT_CHART: AtomicUsize = AtomicUsize::new(0);

/// A stable identity for a chart instance, used to ignore its own sync moves.
pub(crate) fn use_chart_instance() -> usize {
    use_hook(|| NEXT_CHART.fetch_add(1, Ordering::Relaxed))
}

/// Publishes a cursor move to the other charts of `group`.
pub(crate) fn publish_sync(group: &str, origin: usize, x: Option<ChartX>) {
    let mut sync = CHART_SYNC.signal();
    let mut groups = sync.write();
    let sequence = groups.get(group).map_or(0, |entry| entry.sequence + 1);

    groups.insert(
        group.to_string(),
        SyncMove {
            origin,
            x,
            sequence,
        },
    );
}

#[cfg(test)]
mod tests {
    use super::{Inspection, InspectionKey, closest_point, next_index, panel_position, svg_x};
    use crate::charts::model::ChartX;

    fn points() -> Vec<ChartX> {
        vec![ChartX::from("a"), ChartX::from("b"), ChartX::from("c")]
    }

    #[test]
    fn keys_clamp_to_the_first_and_last_points() {
        let points = points();
        assert_eq!(next_index(InspectionKey::Next, None, &points), 0);
        assert_eq!(
            next_index(InspectionKey::Next, Some(&points[0]), &points),
            1
        );
        assert_eq!(
            next_index(InspectionKey::Next, Some(&points[2]), &points),
            2
        );
        assert_eq!(
            next_index(InspectionKey::Previous, Some(&points[0]), &points),
            0
        );
        assert_eq!(
            next_index(InspectionKey::Previous, Some(&points[2]), &points),
            1
        );
        assert_eq!(next_index(InspectionKey::Last, None, &points), 2);
        assert_eq!(
            next_index(InspectionKey::First, Some(&points[2]), &points),
            0
        );
        assert_eq!(
            next_index(InspectionKey::Previous, Some(&ChartX::from("z")), &points),
            0
        );
        assert_eq!(next_index(InspectionKey::Last, None, &[]), 0);
    }

    #[test]
    fn keyboard_pins_and_escape_dismisses() {
        let points = points();
        let mut state = Inspection::default();
        let emit = state.key(InspectionKey::Last, &points).unwrap();
        assert_eq!(emit.x, Some(ChartX::from("c")));
        assert!(emit.announce && state.pinned);
        state.selected = emit.x;
        assert!(state.pointer_move(Some(ChartX::from("a")), false).is_none());
        let escape = state.key(InspectionKey::Escape, &points).unwrap();
        assert_eq!(escape.x, None);
        assert!(state.dismissed && !state.pinned);
        assert!(state.key(InspectionKey::Next, &[]).is_none());
    }

    #[test]
    fn hover_follows_the_pointer_until_it_leaves() {
        let mut state = Inspection::default();
        assert!(state.pointer_move(Some(ChartX::from("a")), true).is_none());
        let hover = state.pointer_move(Some(ChartX::from("a")), false).unwrap();
        assert!(!hover.announce);
        state.selected = hover.x;
        assert!(state.pointer_move(Some(ChartX::from("a")), false).is_none());
        let leave = state.pointer_leave().unwrap();
        assert_eq!(leave.x, None);
        assert!(state.pointer_leave().is_none());
        let pinned = state.pointer_down(Some(ChartX::from("b")));
        assert!(pinned.announce && state.pinned);
        assert!(state.pointer_leave().is_none());
        state.peer_select(Some(ChartX::from("c")));
        assert!(!state.pinned && state.selected == Some(ChartX::from("c")));
    }

    #[test]
    fn pointer_geometry_maps_into_the_view_box() {
        let points = vec![(ChartX::from("a"), 10.0), (ChartX::from("b"), 50.0)];
        assert_eq!(closest_point(28.0, &points), Some(ChartX::from("a")));
        assert_eq!(closest_point(31.0, &points), Some(ChartX::from("b")));
        assert_eq!(closest_point(31.0, &[]), None);
        assert_eq!(
            svg_x(150.0, (100.0, 0.0, 320.0, 120.0), (640.0, 240.0)),
            Some(100.0)
        );
        assert_eq!(svg_x(150.0, (100.0, 0.0, 0.0, 120.0), (640.0, 240.0)), None);
        assert_eq!(
            panel_position((0.0, 0.0, 600.0), (20.0, 40.0, 560.0), 640.0, 200.0, 320.0),
            Some((316.0, 52.0))
        );
        assert_eq!(
            panel_position((0.0, 0.0, 600.0), (20.0, 40.0, 560.0), 640.0, 200.0, 600.0),
            Some((329.0, 52.0))
        );
    }
}