Skip to main content

tui_chart/
sparkline.rs

1//! Inline sparkline using block characters `▁▂▃▄▅▆▇█`.
2
3use crate::canvas::{Canvas, Marker};
4use crate::theme::{self, ChartThemeExt, Theme};
5use ratatui::{
6    buffer::Buffer,
7    layout::Rect,
8    style::{Color, Style},
9    widgets::Block,
10};
11
12const GLYPHS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
13
14/// Rendering style of a [`Sparkline`].
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
16#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
17pub enum SparklineStyle {
18    /// Filled columns made of block characters.
19    #[default]
20    Bar,
21    /// Braille line connecting the points.
22    Line,
23}
24
25/// Compact trend chart, one column per data point (newest points kept when too wide).
26#[derive(Debug, Clone)]
27pub struct Sparkline<'a> {
28    data: Vec<f64>,
29    min: Option<f64>,
30    max: Option<f64>,
31    baseline: Option<f64>,
32    style: SparklineStyle,
33    color: Option<Color>,
34    theme: Option<Theme>,
35    theme_gradient: bool,
36    base: Option<Style>,
37    gradient: Vec<Color>,
38    last_color: Option<Color>,
39    min_color: Option<Color>,
40    max_color: Option<Color>,
41    marker: Marker,
42    block: Option<Block<'a>>,
43}
44
45impl<'a> Sparkline<'a> {
46    /// Create a sparkline from values. Non-finite values are skipped.
47    pub fn new(data: impl IntoIterator<Item = f64>) -> Self {
48        Self {
49            data: data.into_iter().collect(),
50            min: None,
51            max: None,
52            baseline: None,
53            style: SparklineStyle::Bar,
54            color: None,
55            theme: None,
56            theme_gradient: false,
57            base: None,
58            gradient: Vec::new(),
59            last_color: None,
60            min_color: None,
61            max_color: None,
62            marker: Marker::Braille,
63            block: None,
64        }
65    }
66    opt_setter!(
67        /// Fix the lower bound of the scale (default: data minimum).
68        min: f64
69    );
70    opt_setter!(
71        /// Fix the upper bound of the scale (default: data maximum).
72        max: f64
73    );
74    opt_setter!(
75        /// Value bars grow from this baseline (bar style only).
76        baseline: f64
77    );
78    setter!(
79        /// Bar or line style.
80        style: SparklineStyle
81    );
82    opt_setter!(
83        /// Base color.
84        color: Color
85    );
86    theme_setter!(
87        /// Apply a [`Theme`]: base color = accent, background fill. An explicit
88        /// [`Sparkline::color`] wins.
89        theme
90    );
91    setter!(
92        /// Color by value along the theme gradient (needs a theme; an explicit
93        /// [`Sparkline::gradient`] wins).
94        theme_gradient: bool
95    );
96    base_style_setter!(base);
97    /// Color gradient by value, from low to high (overrides base color).
98    pub fn gradient(mut self, colors: impl IntoIterator<Item = Color>) -> Self {
99        self.gradient = colors.into_iter().collect();
100        self
101    }
102    opt_setter!(
103        /// Highlight the last point.
104        highlight_last => last_color: Color
105    );
106    opt_setter!(
107        /// Highlight the minimum point.
108        highlight_min => min_color: Color
109    );
110    opt_setter!(
111        /// Highlight the maximum point.
112        highlight_max => max_color: Color
113    );
114    setter!(
115        /// Glyph family used for dot drawing (default [`Marker::Braille`]).
116        marker: Marker
117    );
118
119    block_setter!(block, 'a);
120
121    fn draw(&self, area: Rect, buf: &mut Buffer) {
122        if area.width == 0 || area.height == 0 {
123            return;
124        }
125        let start = self.data.len().saturating_sub(area.width as usize);
126        let pts: Vec<(usize, f64)> = self.data[start..]
127            .iter()
128            .copied()
129            .enumerate()
130            .filter(|(_, v)| v.is_finite())
131            .collect();
132        if pts.is_empty() {
133            return;
134        }
135        let dmin = pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
136        let dmax = pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max);
137        let lo = self.min.filter(|v| v.is_finite()).unwrap_or(dmin);
138        let mut hi = self.max.filter(|v| v.is_finite()).unwrap_or(dmax);
139        if hi <= lo {
140            hi = lo + 1.0;
141        }
142        let norm = |v: f64| ((v - lo) / (hi - lo)).clamp(0.0, 1.0);
143        let n_last = pts.last().map(|p| p.0);
144        let base = self
145            .color
146            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Cyan, |t| t.accent));
147        let themed: Vec<Color> = match (&self.theme, self.theme_gradient) {
148            (Some(t), true) if self.gradient.is_empty() => {
149                let g = t.gradient();
150                (0..5).map(|i| g.color_at(i as f64 / 4.0)).collect()
151            }
152            _ => Vec::new(),
153        };
154        let grad = if self.gradient.is_empty() {
155            &themed
156        } else {
157            &self.gradient
158        };
159        let color_of = |i: usize, v: f64| {
160            let mut c = base;
161            if !grad.is_empty() {
162                let k = (norm(v) * (grad.len() - 1) as f64).round() as usize;
163                c = grad[k.min(grad.len() - 1)];
164            }
165            if v == dmax {
166                c = self.max_color.unwrap_or(c);
167            }
168            if v == dmin {
169                c = self.min_color.unwrap_or(c);
170            }
171            if Some(i) == n_last {
172                c = self.last_color.unwrap_or(c);
173            }
174            c
175        };
176        match self.style {
177            SparklineStyle::Bar => {
178                let levels = area.height as f64 * 8.0;
179                let base = self.baseline.map(norm).map(|b| (b * levels).round() as i64);
180                for &(i, v) in &pts {
181                    let x = area.x + i as u16;
182                    let top = ((norm(v) * levels).round() as i64).max(1);
183                    let (a, b) = match base {
184                        Some(b) => (b.min(top), b.max(top)),
185                        None => (0, top),
186                    };
187                    let col = color_of(i, v);
188                    for row in 0..area.height as i64 {
189                        let (r0, r1) = (row * 8, row * 8 + 8);
190                        let cov_lo = a.max(r0) - r0;
191                        let cov_hi = b.min(r1) - r0;
192                        if cov_hi <= cov_lo {
193                            continue;
194                        }
195                        let y = area.y + area.height - 1 - row as u16;
196                        let Some(cell) = buf.cell_mut((x, y)) else {
197                            continue;
198                        };
199                        let ch = if cov_lo == 0 && cov_hi < 8 {
200                            GLYPHS[(cov_hi - 1) as usize]
201                        } else if cov_lo > 0 && cov_hi == 8 {
202                            // upper part only: approximate with full block
203                            '█'
204                        } else {
205                            '█'
206                        };
207                        cell.set_char(ch).set_fg(col);
208                    }
209                }
210            }
211            SparklineStyle::Line => {
212                let mut cv = Canvas::new(area.width, area.height, self.marker);
213                let pw = cv.px_w();
214                let ph = cv.px_h();
215                let pos = |i: usize, v: f64| {
216                    (
217                        (i as i32 * self.marker.resolution().0 as i32).min(pw - 1),
218                        ph - 1 - (norm(v) * (ph - 1) as f64).round() as i32,
219                    )
220                };
221                let mut prev: Option<(i32, i32)> = None;
222                for &(i, v) in &pts {
223                    let p = pos(i, v);
224                    let col = color_of(i, v);
225                    match prev {
226                        Some(q) => cv.line(q.0, q.1, p.0, p.1, col),
227                        None => cv.set(p.0, p.1, col),
228                    }
229                    prev = Some(p);
230                }
231                cv.render(buf, area);
232            }
233        }
234    }
235}
236
237impl Sparkline<'_> {
238    fn render_into(&self, area: Rect, buf: &mut Buffer) {
239        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
240        self.draw(inner, buf);
241    }
242}
243
244widget_impls!(Sparkline<'_>);
245
246#[cfg(feature = "theme")]
247impl<'a> tui_nuances::Themed for Sparkline<'a> {
248    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
249        self.theme(theme)
250    }
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256    use ratatui::widgets::Widget;
257
258    fn sym(buf: &Buffer, x: u16, y: u16) -> String {
259        buf[(x, y)].symbol().to_string()
260    }
261
262    #[test]
263    fn single_row_levels() {
264        let area = Rect::new(0, 0, 3, 1);
265        let mut buf = Buffer::empty(area);
266        Sparkline::new([0.0, 4.0, 8.0]).render(area, &mut buf);
267        assert_eq!(sym(&buf, 0, 0), "▁");
268        assert_eq!(sym(&buf, 2, 0), "█");
269    }
270
271    #[test]
272    fn highlights_and_gradient() {
273        let area = Rect::new(0, 0, 3, 1);
274        let mut buf = Buffer::empty(area);
275        Sparkline::new([1.0, 2.0, 3.0])
276            .highlight_last(Color::Red)
277            .highlight_min(Color::Blue)
278            .render(area, &mut buf);
279        assert_eq!(buf[(2, 0)].fg, Color::Red);
280        assert_eq!(buf[(0, 0)].fg, Color::Blue);
281    }
282
283    #[test]
284    fn tall_bars_fill_rows() {
285        let area = Rect::new(0, 0, 2, 3);
286        let mut buf = Buffer::empty(area);
287        Sparkline::new([0.0, 10.0]).min(0.0).render(area, &mut buf);
288        assert_eq!(sym(&buf, 1, 0), "█");
289        assert_eq!(sym(&buf, 1, 2), "█");
290    }
291
292    #[test]
293    fn line_style_and_degenerate() {
294        let area = Rect::new(0, 0, 5, 2);
295        let mut buf = Buffer::empty(area);
296        Sparkline::new([1.0, 2.0, 1.0])
297            .style(SparklineStyle::Line)
298            .render(area, &mut buf);
299        Sparkline::new([f64::NAN, 1.0, f64::INFINITY]).render(area, &mut buf);
300        Sparkline::new(Vec::new()).render(area, &mut buf);
301        Sparkline::new([1.0]).render(Rect::new(0, 0, 0, 0), &mut buf);
302        Sparkline::new([5.0, 5.0]).render(area, &mut buf);
303    }
304
305    #[test]
306    fn keeps_newest_when_narrow() {
307        let area = Rect::new(0, 0, 2, 1);
308        let mut buf = Buffer::empty(area);
309        Sparkline::new([8.0, 0.0, 8.0])
310            .min(0.0)
311            .max(8.0)
312            .render(area, &mut buf);
313        assert_eq!(sym(&buf, 1, 0), "█");
314        assert_eq!(sym(&buf, 0, 0), "▁");
315    }
316}