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 crate::util::darken;
6use ratatui::{
7    buffer::Buffer,
8    layout::Rect,
9    style::{Color, Style},
10    widgets::Block,
11};
12
13const GLYPHS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
14
15/// Rendering style of a [`Sparkline`].
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub enum SparklineStyle {
19    /// Filled columns made of block characters.
20    #[default]
21    Bar,
22    /// Braille line connecting the points.
23    Line,
24    /// Braille line over a dimmed filled area (the classic "stock ticker" look).
25    Area,
26    /// Up / down ticks around the baseline (default 0): wins above, losses below.
27    WinLoss,
28}
29
30/// Compact trend chart, one column per data point (newest points kept when too wide).
31///
32/// # Example
33///
34/// ```
35/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
36/// use tui_chart::{Sparkline};
37///
38/// let chart = Sparkline::new([1.0, 4.0, 2.0, 8.0, 5.0, 7.0]);
39/// let area = Rect::new(0, 0, 40, 12);
40/// let mut buf = Buffer::empty(area);
41/// chart.render(area, &mut buf);
42/// ```
43#[derive(Debug, Clone)]
44pub struct Sparkline<'a> {
45    data: Vec<f64>,
46    min: Option<f64>,
47    max: Option<f64>,
48    baseline: Option<f64>,
49    style: SparklineStyle,
50    color: Option<Color>,
51    theme: Option<Theme>,
52    theme_gradient: bool,
53    base: Option<Style>,
54    gradient: Vec<Color>,
55    last_color: Option<Color>,
56    min_color: Option<Color>,
57    max_color: Option<Color>,
58    marker: Marker,
59    smooth: usize,
60    win_color: Color,
61    loss_color: Color,
62    block: Option<Block<'a>>,
63}
64
65impl<'a> Sparkline<'a> {
66    /// Create a sparkline from values. Non-finite values are skipped.
67    pub fn new(data: impl IntoIterator<Item = f64>) -> Self {
68        Self {
69            data: data.into_iter().collect(),
70            min: None,
71            max: None,
72            baseline: None,
73            style: SparklineStyle::Bar,
74            color: None,
75            theme: None,
76            theme_gradient: false,
77            base: None,
78            gradient: Vec::new(),
79            last_color: None,
80            min_color: None,
81            max_color: None,
82            marker: Marker::Braille,
83            smooth: 1,
84            win_color: Color::Green,
85            loss_color: Color::Red,
86            block: None,
87        }
88    }
89    opt_setter!(
90        /// Fix the lower bound of the scale (default: data minimum).
91        min: f64
92    );
93    opt_setter!(
94        /// Fix the upper bound of the scale (default: data maximum).
95        max: f64
96    );
97    opt_setter!(
98        /// Value bars grow from this baseline (bar style only).
99        baseline: f64
100    );
101    setter!(
102        /// Bar or line style.
103        style: SparklineStyle
104    );
105    opt_setter!(
106        /// Base color.
107        color: Color
108    );
109    theme_setter!(
110        /// Apply a [`Theme`]: base color = accent, background fill. An explicit
111        /// [`Sparkline::color`] wins.
112        theme
113    );
114    setter!(
115        /// Color by value along the theme gradient (needs a theme; an explicit
116        /// [`Sparkline::gradient`] wins).
117        theme_gradient: bool
118    );
119    base_style_setter!(base);
120    /// Color gradient by value, from low to high (overrides base color).
121    pub fn gradient(mut self, colors: impl IntoIterator<Item = Color>) -> Self {
122        self.gradient = colors.into_iter().collect();
123        self
124    }
125    opt_setter!(
126        /// Highlight the last point.
127        highlight_last => last_color: Color
128    );
129    opt_setter!(
130        /// Highlight the minimum point.
131        highlight_min => min_color: Color
132    );
133    opt_setter!(
134        /// Highlight the maximum point.
135        highlight_max => max_color: Color
136    );
137    setter!(
138        /// Glyph family used for dot drawing (default [`Marker::Braille`]).
139        marker: Marker
140    );
141
142    setter!(
143        /// Moving-average window (default 1 = raw); tames noisy series.
144        smooth: usize
145    );
146    /// Colors for [`SparklineStyle::WinLoss`] (win, loss).
147    pub fn win_loss_colors(mut self, win: Color, loss: Color) -> Self {
148        self.win_color = win;
149        self.loss_color = loss;
150        self
151    }
152
153    block_setter!(block, 'a);
154
155    fn draw(&self, area: Rect, buf: &mut Buffer) {
156        if area.width == 0 || area.height == 0 {
157            return;
158        }
159        let start = self.data.len().saturating_sub(area.width as usize);
160        let window = &self.data[start..];
161        let smoothed: Vec<f64>;
162        let window = if self.smooth > 1 {
163            let k = self.smooth;
164            smoothed = (0..window.len())
165                .map(|i| {
166                    let lo = i.saturating_sub(k - 1);
167                    let xs: Vec<f64> = window[lo..=i]
168                        .iter()
169                        .copied()
170                        .filter(|v| v.is_finite())
171                        .collect();
172                    if xs.is_empty() {
173                        f64::NAN
174                    } else {
175                        xs.iter().sum::<f64>() / xs.len() as f64
176                    }
177                })
178                .collect();
179            &smoothed[..]
180        } else {
181            window
182        };
183        let pts: Vec<(usize, f64)> = window
184            .iter()
185            .copied()
186            .enumerate()
187            .filter(|(_, v)| v.is_finite())
188            .collect();
189        if pts.is_empty() {
190            return;
191        }
192        let dmin = pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
193        let dmax = pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max);
194        let lo = self.min.filter(|v| v.is_finite()).unwrap_or(dmin);
195        let mut hi = self.max.filter(|v| v.is_finite()).unwrap_or(dmax);
196        if hi <= lo {
197            hi = lo + 1.0;
198        }
199        let norm = |v: f64| ((v - lo) / (hi - lo)).clamp(0.0, 1.0);
200        let n_last = pts.last().map(|p| p.0);
201        if crate::interact::recording() {
202            for &(i, v) in &pts {
203                let rect = Rect::new(area.x + i as u16, area.y, 1, area.height);
204                crate::interact::record_point(rect, 0, start + i, || {
205                    (
206                        format!("#{}", start + i),
207                        vec![crate::util::format_compact(v)],
208                    )
209                });
210            }
211        }
212        let base = self
213            .color
214            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Cyan, |t| t.accent));
215        let themed: Vec<Color> = match (&self.theme, self.theme_gradient) {
216            (Some(t), true) if self.gradient.is_empty() => {
217                let g = t.gradient();
218                (0..5).map(|i| g.color_at(i as f64 / 4.0)).collect()
219            }
220            _ => Vec::new(),
221        };
222        let grad = if self.gradient.is_empty() {
223            &themed
224        } else {
225            &self.gradient
226        };
227        let color_of = |i: usize, v: f64| {
228            let mut c = base;
229            if !grad.is_empty() {
230                let k = (norm(v) * (grad.len() - 1) as f64).round() as usize;
231                c = grad[k.min(grad.len() - 1)];
232            }
233            if v == dmax {
234                c = self.max_color.unwrap_or(c);
235            }
236            if v == dmin {
237                c = self.min_color.unwrap_or(c);
238            }
239            if Some(i) == n_last {
240                c = self.last_color.unwrap_or(c);
241            }
242            c
243        };
244        match self.style {
245            SparklineStyle::Bar => {
246                let levels = area.height as f64 * 8.0;
247                let base = self.baseline.map(norm).map(|b| (b * levels).round() as i64);
248                for &(i, v) in &pts {
249                    let x = area.x + i as u16;
250                    let top = ((norm(v) * levels).round() as i64).max(1);
251                    let (a, b) = match base {
252                        Some(b) => (b.min(top), b.max(top)),
253                        None => (0, top),
254                    };
255                    let col = color_of(i, v);
256                    for row in 0..area.height as i64 {
257                        let (r0, r1) = (row * 8, row * 8 + 8);
258                        let cov_lo = a.max(r0) - r0;
259                        let cov_hi = b.min(r1) - r0;
260                        if cov_hi <= cov_lo {
261                            continue;
262                        }
263                        let y = area.y + area.height - 1 - row as u16;
264                        let Some(cell) = buf.cell_mut((x, y)) else {
265                            continue;
266                        };
267                        let ch = if cov_lo == 0 && cov_hi < 8 {
268                            GLYPHS[(cov_hi - 1) as usize]
269                        } else if cov_lo > 0 && cov_hi == 8 {
270                            // upper part only: approximate with full block
271                            '█'
272                        } else {
273                            '█'
274                        };
275                        cell.set_char(ch).set_fg(col);
276                    }
277                }
278            }
279            SparklineStyle::WinLoss => {
280                let b = self.baseline.unwrap_or(0.0);
281                let mid = area.height / 2;
282                for &(i, v) in &pts {
283                    let x = area.x + i as u16;
284                    let win = v >= b;
285                    let col = if win { self.win_color } else { self.loss_color };
286                    if area.height == 1 {
287                        if let Some(c) = buf.cell_mut((x, area.y)) {
288                            c.set_char(if win { '▀' } else { '▄' }).set_fg(col);
289                        }
290                        continue;
291                    }
292                    // odd heights keep the centre row as an axis dash
293                    let (r0, r1) = if win {
294                        (0, mid)
295                    } else {
296                        (area.height - mid, area.height)
297                    };
298                    for r in r0..r1 {
299                        if let Some(c) = buf.cell_mut((x, area.y + r)) {
300                            c.set_char('█').set_fg(col);
301                        }
302                    }
303                    if area.height % 2 == 1 {
304                        if let Some(c) = buf.cell_mut((x, area.y + mid)) {
305                            c.set_char('─').set_fg(darken(col, 0.5));
306                        }
307                    }
308                }
309            }
310            SparklineStyle::Line | SparklineStyle::Area => {
311                if self.style == SparklineStyle::Area {
312                    let levels = area.height as f64 * 8.0;
313                    for &(i, v) in &pts {
314                        let x = area.x + i as u16;
315                        let top = (norm(v) * levels).round() as i64;
316                        let dim = darken(color_of(i, v), 0.6);
317                        for row in 0..area.height as i64 {
318                            let cov = top - row * 8;
319                            if cov <= 0 {
320                                break;
321                            }
322                            let y = area.y + area.height - 1 - row as u16;
323                            if let Some(cell) = buf.cell_mut((x, y)) {
324                                if cov >= 8 {
325                                    cell.set_char(' ').set_bg(dim);
326                                } else {
327                                    cell.set_char(GLYPHS[(cov - 1) as usize]).set_fg(dim);
328                                }
329                            }
330                        }
331                    }
332                }
333                let mut cv = Canvas::new(area.width, area.height, self.marker);
334                let pw = cv.px_w();
335                let ph = cv.px_h();
336                let pos = |i: usize, v: f64| {
337                    (
338                        (i as i32 * self.marker.resolution().0 as i32).min(pw - 1),
339                        ph - 1 - (norm(v) * (ph - 1) as f64).round() as i32,
340                    )
341                };
342                let mut prev: Option<(i32, i32)> = None;
343                for &(i, v) in &pts {
344                    let p = pos(i, v);
345                    let col = color_of(i, v);
346                    match prev {
347                        Some(q) => cv.line(q.0, q.1, p.0, p.1, col),
348                        None => cv.set(p.0, p.1, col),
349                    }
350                    prev = Some(p);
351                }
352                cv.render(buf, area);
353            }
354        }
355    }
356}
357
358impl Sparkline<'_> {
359    fn render_into(&self, area: Rect, buf: &mut Buffer) {
360        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
361        self.draw(inner, buf);
362    }
363}
364
365widget_impls!(Sparkline<'_>);
366
367#[cfg(feature = "theme")]
368impl<'a> tui_nuances::Themed for Sparkline<'a> {
369    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
370        self.theme(theme)
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377    use ratatui::widgets::Widget;
378
379    fn sym(buf: &Buffer, x: u16, y: u16) -> String {
380        buf[(x, y)].symbol().to_string()
381    }
382
383    #[test]
384    fn single_row_levels() {
385        let area = Rect::new(0, 0, 3, 1);
386        let mut buf = Buffer::empty(area);
387        Sparkline::new([0.0, 4.0, 8.0]).render(area, &mut buf);
388        assert_eq!(sym(&buf, 0, 0), "▁");
389        assert_eq!(sym(&buf, 2, 0), "█");
390    }
391
392    #[test]
393    fn highlights_and_gradient() {
394        let area = Rect::new(0, 0, 3, 1);
395        let mut buf = Buffer::empty(area);
396        Sparkline::new([1.0, 2.0, 3.0])
397            .highlight_last(Color::Red)
398            .highlight_min(Color::Blue)
399            .render(area, &mut buf);
400        assert_eq!(buf[(2, 0)].fg, Color::Red);
401        assert_eq!(buf[(0, 0)].fg, Color::Blue);
402    }
403
404    #[test]
405    fn tall_bars_fill_rows() {
406        let area = Rect::new(0, 0, 2, 3);
407        let mut buf = Buffer::empty(area);
408        Sparkline::new([0.0, 10.0]).min(0.0).render(area, &mut buf);
409        assert_eq!(sym(&buf, 1, 0), "█");
410        assert_eq!(sym(&buf, 1, 2), "█");
411    }
412
413    #[test]
414    fn line_style_and_degenerate() {
415        let area = Rect::new(0, 0, 5, 2);
416        let mut buf = Buffer::empty(area);
417        Sparkline::new([1.0, 2.0, 1.0])
418            .style(SparklineStyle::Line)
419            .render(area, &mut buf);
420        Sparkline::new([f64::NAN, 1.0, f64::INFINITY]).render(area, &mut buf);
421        Sparkline::new(Vec::new()).render(area, &mut buf);
422        Sparkline::new([1.0]).render(Rect::new(0, 0, 0, 0), &mut buf);
423        Sparkline::new([5.0, 5.0]).render(area, &mut buf);
424    }
425
426    #[test]
427    fn area_fills_below_line_and_winloss_splits() {
428        let area = Rect::new(0, 0, 3, 3);
429        let mut buf = Buffer::empty(area);
430        Sparkline::new([10.0, 10.0, 10.0])
431            .min(0.0)
432            .style(SparklineStyle::Area)
433            .render(area, &mut buf);
434        assert_ne!(buf[(1, 2)].bg, Color::Reset); // filled under the line
435        let mut buf = Buffer::empty(Rect::new(0, 0, 2, 4));
436        Sparkline::new([1.0, -1.0])
437            .style(SparklineStyle::WinLoss)
438            .render(Rect::new(0, 0, 2, 4), &mut buf);
439        assert_eq!(sym(&buf, 0, 0), "█");
440        assert_eq!(sym(&buf, 0, 3), " ");
441        assert_eq!(sym(&buf, 1, 3), "█");
442        assert_eq!(buf[(1, 3)].fg, Color::Red);
443    }
444
445    #[test]
446    fn smoothing_averages() {
447        let area = Rect::new(0, 0, 3, 1);
448        let mut buf = Buffer::empty(area);
449        Sparkline::new([0.0, 8.0, 0.0, 8.0])
450            .smooth(2)
451            .min(0.0)
452            .max(8.0)
453            .render(area, &mut buf);
454        assert_eq!(sym(&buf, 2, 0), "▄"); // mean of 8 and 0
455    }
456
457    #[test]
458    fn keeps_newest_when_narrow() {
459        let area = Rect::new(0, 0, 2, 1);
460        let mut buf = Buffer::empty(area);
461        Sparkline::new([8.0, 0.0, 8.0])
462            .min(0.0)
463            .max(8.0)
464            .render(area, &mut buf);
465        assert_eq!(sym(&buf, 1, 0), "█");
466        assert_eq!(sym(&buf, 0, 0), "▁");
467    }
468}