Skip to main content

scope_cli/cli/
charts.rs

1//! The one chart component of the TUI and the monitor (#58).
2//!
3//! [`Sparkline`] draws a series as bars, with a gap where a value is
4//! missing and a line where its threshold is. [`HealthStrip`] draws one
5//! `✓` or `✗` per run. Both show the newest values that fit, at the right
6//! edge. Styles come from the caller (theme roles); nothing here names a
7//! color.
8
9use crate::cli::theme::{ERR, OK, SECONDARY};
10use ratatui::buffer::Buffer;
11use ratatui::layout::Rect;
12use ratatui::style::Style;
13use ratatui::widgets::Widget;
14use scope::metrics::Threshold;
15
16/// Bar glyphs from 1/8 to a full cell.
17const BARS: [&str; 8] = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];
18
19/// Eighths of a cell, the vertical step of a bar.
20const STEPS_PER_ROW: u32 = 8;
21
22/// The glyph of a threshold line in the cells no bar fills.
23const THRESHOLD_GLYPH: &str = "─";
24
25/// A run that passed and one that failed, in a [`HealthStrip`].
26const PASS_GLYPH: &str = "✓";
27const FAIL_GLYPH: &str = "✗";
28
29/// A series as bars. `None` is a gap, never a zero.
30pub struct Sparkline<'a> {
31    values: &'a [Option<f64>],
32    threshold: Option<Threshold>,
33    style: Style,
34    track: bool,
35    min_span: Option<f64>,
36}
37
38impl<'a> Sparkline<'a> {
39    /// Bars of `values` (oldest first) in `style`.
40    pub fn new(values: &'a [Option<f64>], style: Style) -> Self {
41        Self {
42            values,
43            threshold: None,
44            style,
45            track: false,
46            min_span: None,
47        }
48    }
49
50    /// The smallest range the scale shows. A series that moves less than
51    /// `span` is drawn around the middle of the chart, so noise reads as a
52    /// flat line, not as full and empty bars.
53    pub fn min_span(mut self, span: f64) -> Self {
54        self.min_span = Some(span).filter(|s| s.is_finite() && *s > 0.0);
55        self
56    }
57
58    /// Track mode (#58 market view, J4): the bars fill a `─` track from the
59    /// left, one cell per run, and scroll when it is full. A bar outside the
60    /// threshold (above a `Max`, below a `Min`) is drawn in the error color;
61    /// no threshold line is drawn.
62    pub fn track(mut self) -> Self {
63        self.track = true;
64        self
65    }
66
67    /// Adds the line of `threshold`, when there is one.
68    pub fn threshold(mut self, threshold: Option<Threshold>) -> Self {
69        self.threshold = threshold;
70        self
71    }
72}
73
74/// The value a threshold draws its line at.
75fn threshold_value(t: Threshold) -> f64 {
76    match t {
77        Threshold::Max(v) | Threshold::Min(v) | Threshold::Target(v) => v,
78    }
79}
80
81/// The newest `width` items of `items`.
82fn newest<T>(items: &[T], width: usize) -> &[T] {
83    &items[items.len().saturating_sub(width)..]
84}
85
86impl Widget for Sparkline<'_> {
87    fn render(self, area: Rect, buf: &mut Buffer) {
88        if area.is_empty() {
89            return;
90        }
91        let shown = newest(self.values, area.width as usize);
92        let line = self
93            .threshold
94            .map(threshold_value)
95            .filter(|v| v.is_finite());
96        let known = shown.iter().flatten().copied().filter(|v| v.is_finite());
97        let (mut lo, mut hi) = known.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| {
98            (lo.min(v), hi.max(v))
99        });
100        if let Some(t) = line.filter(|_| !self.track) {
101            // The scale includes the threshold, so its line is on the chart.
102            lo = lo.min(t);
103            hi = hi.max(t);
104        }
105        if !lo.is_finite() {
106            return; // no value to draw
107        }
108        if let Some(span) = self.min_span
109            && hi - lo < span
110        {
111            let mid = (lo + hi) / 2.0;
112            lo = mid - span / 2.0;
113            hi = mid + span / 2.0;
114        }
115        let steps = u32::from(area.height) * STEPS_PER_ROW;
116        let range = hi - lo;
117        // A flat series draws half height: it is there, but not high or low.
118        let height_of = |v: f64| -> u32 {
119            if range <= 0.0 {
120                return steps / 2;
121            }
122            let h = ((v - lo) / range * f64::from(steps - 1)).round() as u32 + 1;
123            h.min(steps)
124        };
125        let x0 = if self.track {
126            area.left()
127        } else {
128            area.right() - shown.len() as u16
129        };
130        if self.track {
131            // The empty track: what the coming runs will fill.
132            let row = area.bottom() - 1;
133            for x in x0 + shown.len() as u16..area.right() {
134                buf[(x, row)]
135                    .set_symbol(THRESHOLD_GLYPH)
136                    .set_style(SECONDARY);
137            }
138        }
139        for (i, value) in shown.iter().enumerate() {
140            let x = x0 + i as u16;
141            let Some(v) = value.filter(|v| v.is_finite()) else {
142                continue; // a gap
143            };
144            let style = match (self.track, self.threshold) {
145                (true, Some(Threshold::Max(t))) if v > t => ERR,
146                (true, Some(Threshold::Min(t))) if v < t => ERR,
147                _ => self.style,
148            };
149            let mut left = height_of(v);
150            for row in (area.top()..area.bottom()).rev() {
151                if left == 0 {
152                    break;
153                }
154                let eighths = left.min(STEPS_PER_ROW);
155                buf[(x, row)]
156                    .set_symbol(BARS[eighths as usize - 1])
157                    .set_style(style);
158                left -= eighths;
159            }
160        }
161        if let Some(t) = line.filter(|_| !self.track) {
162            let rows_up = height_of(t).saturating_sub(1) / STEPS_PER_ROW;
163            let row = area.bottom() - 1 - rows_up as u16;
164            for x in area.left()..area.right() {
165                let cell = &mut buf[(x, row)];
166                if cell.symbol() == " " {
167                    cell.set_symbol(THRESHOLD_GLYPH).set_style(SECONDARY);
168                }
169            }
170        }
171    }
172}
173
174/// One `✓` or `✗` per run, the newest at the right.
175pub struct HealthStrip<'a> {
176    runs: &'a [bool],
177    track: bool,
178}
179
180impl<'a> HealthStrip<'a> {
181    /// A strip of `runs` (true = healthy), oldest first.
182    pub fn new(runs: &'a [bool]) -> Self {
183        Self { runs, track: false }
184    }
185
186    /// Track mode: from the left over a `─` track, as [`Sparkline::track`].
187    pub fn track(mut self) -> Self {
188        self.track = true;
189        self
190    }
191}
192
193impl Widget for HealthStrip<'_> {
194    fn render(self, area: Rect, buf: &mut Buffer) {
195        if area.is_empty() {
196            return;
197        }
198        let shown = newest(self.runs, area.width as usize);
199        let x0 = if self.track {
200            for x in area.left() + shown.len() as u16..area.right() {
201                buf[(x, area.top())]
202                    .set_symbol(THRESHOLD_GLYPH)
203                    .set_style(SECONDARY);
204            }
205            area.left()
206        } else {
207            area.right() - shown.len() as u16
208        };
209        for (i, healthy) in shown.iter().enumerate() {
210            let (glyph, style) = if *healthy {
211                (PASS_GLYPH, OK)
212            } else {
213                (FAIL_GLYPH, ERR)
214            };
215            buf[(x0 + i as u16, area.top())]
216                .set_symbol(glyph)
217                .set_style(style);
218        }
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    fn draw(widget: impl Widget, width: u16, height: u16) -> Vec<String> {
227        let area = Rect::new(0, 0, width, height);
228        let mut buf = Buffer::empty(area);
229        widget.render(area, &mut buf);
230        (0..height)
231            .map(|y| {
232                (0..width)
233                    .map(|x| buf[(x, y)].symbol().to_string())
234                    .collect()
235            })
236            .collect()
237    }
238
239    #[test]
240    fn test_track_fills_from_the_left_then_scrolls() {
241        let values = [Some(1.0), Some(2.0)];
242        let rows = draw(Sparkline::new(&values, Style::new()).track(), 6, 1);
243        assert_eq!(rows[0], "▁█────", "{rows:?}");
244        let values: Vec<Option<f64>> = (1..=8).map(|v| Some(f64::from(v))).collect();
245        let rows = draw(Sparkline::new(&values, Style::new()).track(), 4, 1);
246        assert!(!rows[0].contains('─'), "a full track scrolls: {rows:?}");
247        assert!(
248            rows[0].ends_with('█'),
249            "the newest at the right edge: {rows:?}"
250        );
251    }
252
253    #[test]
254    fn test_track_colors_a_bar_outside_its_limit_and_draws_no_threshold_line() {
255        let values = [Some(1.0), Some(5.0)];
256        let area = Rect::new(0, 0, 4, 2);
257        let mut buf = Buffer::empty(area);
258        Sparkline::new(&values, OK)
259            .threshold(Some(Threshold::Max(3.0)))
260            .track()
261            .render(area, &mut buf);
262        assert_eq!(buf[(0, 1)].style().fg, OK.fg, "within the limit");
263        assert_eq!(buf[(1, 1)].style().fg, ERR.fg, "above the max");
264        // The only `─` cells are the empty track on the bottom row.
265        assert_eq!(buf[(2, 0)].symbol(), " ");
266        assert_eq!(buf[(2, 1)].symbol(), "─");
267    }
268
269    #[test]
270    fn test_noise_under_the_min_span_reads_flat() {
271        // Depth moving 0.1% must not draw full and empty bars.
272        let values = [Some(1000.0), Some(1001.0), Some(1000.5)];
273        let rows = draw(Sparkline::new(&values, Style::new()).min_span(100.0), 3, 1);
274        let heights: Vec<usize> = rows[0]
275            .chars()
276            .map(|c| BARS.iter().position(|b| b.starts_with(c)).unwrap())
277            .collect();
278        assert!(
279            heights.iter().all(|h| (3..=4).contains(h)),
280            "near the middle: {rows:?}"
281        );
282        // A real move larger than the span still fills the scale.
283        let values = [Some(1000.0), Some(1500.0)];
284        let rows = draw(Sparkline::new(&values, Style::new()).min_span(100.0), 2, 1);
285        assert_eq!(rows[0], "▁█", "{rows:?}");
286    }
287
288    #[test]
289    fn test_health_strip_track_fills_from_the_left() {
290        let rows = draw(HealthStrip::new(&[true, false]).track(), 5, 1);
291        assert_eq!(rows[0], "✓✗───");
292    }
293
294    #[test]
295    fn test_a_missing_value_is_a_gap_not_a_zero() {
296        let values = [Some(1.0), None, Some(3.0)];
297        let rows = draw(Sparkline::new(&values, Style::new()), 3, 1);
298        let cells: Vec<char> = rows[0].chars().collect();
299        assert_eq!(cells[1], ' ', "{rows:?}");
300        assert_ne!(cells[0], ' ');
301        assert_eq!(cells[2], '█', "the top value fills its cell");
302    }
303
304    #[test]
305    fn test_only_the_newest_values_that_fit_are_drawn() {
306        // The first value is far above the rest. If it were drawn, the
307        // others would be short bars; cut off, the scale is theirs alone.
308        let values = [Some(100.0), Some(1.0), Some(2.0)];
309        let rows = draw(Sparkline::new(&values, Style::new()), 2, 1);
310        assert_eq!(rows[0], "▁█", "{rows:?}");
311    }
312
313    #[test]
314    fn test_the_threshold_line_fills_the_empty_cells_of_its_row() {
315        // Values 0 and 10 over 2 rows; a max of 8 sits in the top row.
316        let values = [Some(0.0), Some(10.0), Some(0.0)];
317        let chart = Sparkline::new(&values, Style::new()).threshold(Some(Threshold::Max(8.0)));
318        let rows = draw(chart, 3, 2);
319        assert_eq!(rows[0], "─█─", "{rows:?}");
320        assert!(!rows[1].contains('─'), "{rows:?}");
321    }
322
323    #[test]
324    fn test_the_scale_includes_a_threshold_beyond_the_values() {
325        // A min depth of 100 with depths near 10: the line is at the top
326        // and the bars stay low, so the shortfall shows.
327        let values = [Some(10.0), Some(12.0)];
328        let chart = Sparkline::new(&values, Style::new()).threshold(Some(Threshold::Min(100.0)));
329        let rows = draw(chart, 2, 2);
330        assert_eq!(rows[0], "──", "{rows:?}");
331        assert!(rows[1].chars().all(|c| c != '█'), "{rows:?}");
332    }
333
334    #[test]
335    fn test_no_values_draw_nothing() {
336        let values = [None, None];
337        let rows = draw(Sparkline::new(&values, Style::new()), 2, 1);
338        assert_eq!(rows[0], "  ");
339    }
340
341    #[test]
342    fn test_the_health_strip_marks_each_run_newest_last() {
343        let runs = [true, false, true, true];
344        let rows = draw(HealthStrip::new(&runs), 3, 1);
345        assert_eq!(rows[0], "✗✓✓");
346    }
347}