Skip to main content

tui_chart/
crosshair.rs

1//! Crosshair cursor with value tooltip, plus nearest-point lookup.
2
3use crate::layout::text_width;
4use ratatui::{
5    buffer::Buffer,
6    layout::Rect,
7    style::{Color, Style},
8};
9
10/// A cursor position in data coordinates, drawn as guide lines + tooltip.
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub struct Crosshair {
13    /// Cursor x in data coordinates.
14    pub x: f64,
15    /// Cursor y in data coordinates.
16    pub y: f64,
17    /// Style of the guide lines.
18    pub style: Style,
19    /// Style of the tooltip box.
20    pub tooltip_style: Style,
21    /// Draw the value tooltip (default true).
22    pub tooltip: bool,
23}
24
25impl Crosshair {
26    /// Crosshair at data `(x, y)`.
27    pub fn new(x: f64, y: f64) -> Self {
28        Self {
29            x,
30            y,
31            style: Style::default().fg(Color::Gray),
32            tooltip_style: Style::default().fg(Color::White).bg(Color::DarkGray),
33            tooltip: true,
34        }
35    }
36
37    /// Copy with theme crosshair/tooltip colors for styles still at their
38    /// defaults (explicitly set styles are kept).
39    pub(crate) fn with_theme(&self, t: &crate::theme::Theme) -> Self {
40        let d = Crosshair::new(self.x, self.y);
41        let mut c = *self;
42        if c.style == d.style {
43            c.style = Style::default().fg(t.crosshair);
44        }
45        if c.tooltip_style == d.tooltip_style {
46            c.tooltip_style = Style::default().fg(t.tooltip_fg).bg(t.tooltip_bg);
47        }
48        c
49    }
50
51    /// Use the theme's crosshair/tooltip colors for styles still at their
52    /// defaults; explicit [`style`](Self::style) / [`tooltip_style`](Self::tooltip_style)
53    /// win regardless of call order.
54    #[must_use]
55    #[cfg(feature = "theme")]
56    pub fn theme(self, theme: impl Into<crate::theme::Theme>) -> Self {
57        self.with_theme(&theme.into())
58    }
59
60    setter!(
61        /// Guide line style.
62        style: Style
63    );
64
65    setter!(
66        /// Tooltip style.
67        tooltip_style: Style
68    );
69
70    setter!(
71        /// Show or hide the tooltip.
72        tooltip: bool
73    );
74}
75
76/// Result of a nearest-point lookup.
77#[derive(Debug, Clone, Copy, PartialEq)]
78pub struct NearestPoint {
79    /// Series index.
80    pub series: usize,
81    /// Point index within the series.
82    pub index: usize,
83    /// Point x (data coordinates).
84    pub x: f64,
85    /// Point y (data coordinates).
86    pub y: f64,
87}
88
89/// Index and distance of the point closest to `target`, with each axis divided
90/// by `scale` (so distances are comparable). Non-finite points are skipped.
91pub fn nearest_point(
92    points: impl IntoIterator<Item = (f64, f64)>,
93    target: (f64, f64),
94    scale: (f64, f64),
95) -> Option<(usize, f64)> {
96    let sx = if scale.0.is_finite() && scale.0 > 0.0 {
97        scale.0
98    } else {
99        1.0
100    };
101    let sy = if scale.1.is_finite() && scale.1 > 0.0 {
102        scale.1
103    } else {
104        1.0
105    };
106    points
107        .into_iter()
108        .enumerate()
109        .filter(|(_, (x, y))| x.is_finite() && y.is_finite())
110        .map(|(i, (x, y))| {
111            let (dx, dy) = ((x - target.0) / sx, (y - target.1) / sy);
112            (i, (dx * dx + dy * dy).sqrt())
113        })
114        .filter(|(_, d)| d.is_finite())
115        .min_by(|a, b| a.1.total_cmp(&b.1))
116}
117
118/// Draw guide lines through cell `(col, row)` (relative to `plot`) and an
119/// optional tooltip with `lines`. Out-of-plot positions draw nothing.
120pub(crate) fn draw(
121    buf: &mut Buffer,
122    plot: Rect,
123    ch: &Crosshair,
124    col: i32,
125    row: i32,
126    lines: &[String],
127) {
128    let (w, h) = (plot.width as i32, plot.height as i32);
129    if w == 0 || h == 0 || !(0..w).contains(&col) || !(0..h).contains(&row) {
130        return;
131    }
132    let mut put = |c: i32, r: i32, glyph: &str| {
133        if let Some(cell) = buf.cell_mut((plot.x + c as u16, plot.y + r as u16)) {
134            if matches!(cell.symbol(), " " | "·" | "╌" | "╎") {
135                cell.set_symbol(glyph).set_style(ch.style);
136            }
137        }
138    };
139    for c in 0..w {
140        put(c, row, "┄");
141    }
142    for r in 0..h {
143        put(col, r, "┆");
144    }
145    if let Some(cell) = buf.cell_mut((plot.x + col as u16, plot.y + row as u16)) {
146        if matches!(cell.symbol(), " " | "·" | "┄" | "┆") {
147            cell.set_symbol("┼").set_style(ch.style);
148        }
149    }
150    if !ch.tooltip || lines.is_empty() {
151        return;
152    }
153    let tw = lines
154        .iter()
155        .map(|l| text_width(l) as i32)
156        .max()
157        .unwrap_or(0)
158        + 2;
159    let th = lines.len() as i32;
160    if tw > w || th > h {
161        return;
162    }
163    let mut x = col + 2;
164    if x + tw > w {
165        x = col - 1 - tw;
166    }
167    let mut y = row + 1;
168    if y + th > h {
169        y = row - th;
170    }
171    let (x, y) = (x.clamp(0, w - tw), y.clamp(0, h - th));
172    for (i, l) in lines.iter().enumerate() {
173        let (cx, cy) = (plot.x + x as u16, plot.y + (y + i as i32) as u16);
174        for k in 0..tw {
175            if let Some(cell) = buf.cell_mut((cx + k as u16, cy)) {
176                cell.set_symbol(" ").set_style(ch.tooltip_style);
177            }
178        }
179        buf.set_stringn(cx + 1, cy, l, (tw - 2) as usize, ch.tooltip_style);
180    }
181}
182
183#[cfg(feature = "theme")]
184impl tui_nuances::Themed for Crosshair {
185    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
186        self.with_theme(theme)
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn nearest_basic() {
196        let pts = [(0.0, 0.0), (5.0, 5.0), (f64::NAN, 1.0), (9.0, 9.0)];
197        assert_eq!(nearest_point(pts, (4.0, 4.0), (1.0, 1.0)).unwrap().0, 1);
198        assert_eq!(nearest_point(pts, (8.0, 8.0), (1.0, 1.0)).unwrap().0, 3);
199        assert!(nearest_point([], (0.0, 0.0), (1.0, 1.0)).is_none());
200        assert!(nearest_point([(f64::NAN, f64::NAN)], (0.0, 0.0), (0.0, 0.0)).is_none());
201    }
202
203    #[test]
204    fn draws_guides_and_tooltip() {
205        let plot = Rect::new(0, 0, 20, 8);
206        let mut buf = Buffer::empty(plot);
207        let ch = Crosshair::new(0.0, 0.0);
208        draw(&mut buf, plot, &ch, 5, 3, &["x 1".into(), "y 2".into()]);
209        assert_eq!(buf[(5, 3)].symbol(), "┼");
210        assert_eq!(buf[(5, 0)].symbol(), "┆");
211        assert_eq!(buf[(8, 4)].symbol(), "x");
212    }
213
214    #[test]
215    fn edge_and_outside_safe() {
216        let plot = Rect::new(0, 0, 6, 3);
217        let mut buf = Buffer::empty(plot);
218        let ch = Crosshair::new(0.0, 0.0);
219        draw(&mut buf, plot, &ch, 5, 2, &["long tooltip line".into()]);
220        draw(&mut buf, plot, &ch, -1, 9, &["a".into()]);
221        draw(&mut buf, Rect::new(0, 0, 0, 0), &ch, 0, 0, &[]);
222    }
223}