1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub enum SparklineStyle {
19 #[default]
21 Bar,
22 Line,
24 Area,
26 WinLoss,
28}
29
30#[derive(Debug, Clone)]
32pub struct Sparkline<'a> {
33 data: Vec<f64>,
34 min: Option<f64>,
35 max: Option<f64>,
36 baseline: Option<f64>,
37 style: SparklineStyle,
38 color: Option<Color>,
39 theme: Option<Theme>,
40 theme_gradient: bool,
41 base: Option<Style>,
42 gradient: Vec<Color>,
43 last_color: Option<Color>,
44 min_color: Option<Color>,
45 max_color: Option<Color>,
46 marker: Marker,
47 smooth: usize,
48 win_color: Color,
49 loss_color: Color,
50 block: Option<Block<'a>>,
51}
52
53impl<'a> Sparkline<'a> {
54 pub fn new(data: impl IntoIterator<Item = f64>) -> Self {
56 Self {
57 data: data.into_iter().collect(),
58 min: None,
59 max: None,
60 baseline: None,
61 style: SparklineStyle::Bar,
62 color: None,
63 theme: None,
64 theme_gradient: false,
65 base: None,
66 gradient: Vec::new(),
67 last_color: None,
68 min_color: None,
69 max_color: None,
70 marker: Marker::Braille,
71 smooth: 1,
72 win_color: Color::Green,
73 loss_color: Color::Red,
74 block: None,
75 }
76 }
77 opt_setter!(
78 min: f64
80 );
81 opt_setter!(
82 max: f64
84 );
85 opt_setter!(
86 baseline: f64
88 );
89 setter!(
90 style: SparklineStyle
92 );
93 opt_setter!(
94 color: Color
96 );
97 theme_setter!(
98 theme
101 );
102 setter!(
103 theme_gradient: bool
106 );
107 base_style_setter!(base);
108 pub fn gradient(mut self, colors: impl IntoIterator<Item = Color>) -> Self {
110 self.gradient = colors.into_iter().collect();
111 self
112 }
113 opt_setter!(
114 highlight_last => last_color: Color
116 );
117 opt_setter!(
118 highlight_min => min_color: Color
120 );
121 opt_setter!(
122 highlight_max => max_color: Color
124 );
125 setter!(
126 marker: Marker
128 );
129
130 setter!(
131 smooth: usize
133 );
134 pub fn win_loss_colors(mut self, win: Color, loss: Color) -> Self {
136 self.win_color = win;
137 self.loss_color = loss;
138 self
139 }
140
141 block_setter!(block, 'a);
142
143 fn draw(&self, area: Rect, buf: &mut Buffer) {
144 if area.width == 0 || area.height == 0 {
145 return;
146 }
147 let start = self.data.len().saturating_sub(area.width as usize);
148 let window = &self.data[start..];
149 let smoothed: Vec<f64>;
150 let window = if self.smooth > 1 {
151 let k = self.smooth;
152 smoothed = (0..window.len())
153 .map(|i| {
154 let lo = i.saturating_sub(k - 1);
155 let xs: Vec<f64> = window[lo..=i]
156 .iter()
157 .copied()
158 .filter(|v| v.is_finite())
159 .collect();
160 if xs.is_empty() {
161 f64::NAN
162 } else {
163 xs.iter().sum::<f64>() / xs.len() as f64
164 }
165 })
166 .collect();
167 &smoothed[..]
168 } else {
169 window
170 };
171 let pts: Vec<(usize, f64)> = window
172 .iter()
173 .copied()
174 .enumerate()
175 .filter(|(_, v)| v.is_finite())
176 .collect();
177 if pts.is_empty() {
178 return;
179 }
180 let dmin = pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
181 let dmax = pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max);
182 let lo = self.min.filter(|v| v.is_finite()).unwrap_or(dmin);
183 let mut hi = self.max.filter(|v| v.is_finite()).unwrap_or(dmax);
184 if hi <= lo {
185 hi = lo + 1.0;
186 }
187 let norm = |v: f64| ((v - lo) / (hi - lo)).clamp(0.0, 1.0);
188 let n_last = pts.last().map(|p| p.0);
189 let base = self
190 .color
191 .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Cyan, |t| t.accent));
192 let themed: Vec<Color> = match (&self.theme, self.theme_gradient) {
193 (Some(t), true) if self.gradient.is_empty() => {
194 let g = t.gradient();
195 (0..5).map(|i| g.color_at(i as f64 / 4.0)).collect()
196 }
197 _ => Vec::new(),
198 };
199 let grad = if self.gradient.is_empty() {
200 &themed
201 } else {
202 &self.gradient
203 };
204 let color_of = |i: usize, v: f64| {
205 let mut c = base;
206 if !grad.is_empty() {
207 let k = (norm(v) * (grad.len() - 1) as f64).round() as usize;
208 c = grad[k.min(grad.len() - 1)];
209 }
210 if v == dmax {
211 c = self.max_color.unwrap_or(c);
212 }
213 if v == dmin {
214 c = self.min_color.unwrap_or(c);
215 }
216 if Some(i) == n_last {
217 c = self.last_color.unwrap_or(c);
218 }
219 c
220 };
221 match self.style {
222 SparklineStyle::Bar => {
223 let levels = area.height as f64 * 8.0;
224 let base = self.baseline.map(norm).map(|b| (b * levels).round() as i64);
225 for &(i, v) in &pts {
226 let x = area.x + i as u16;
227 let top = ((norm(v) * levels).round() as i64).max(1);
228 let (a, b) = match base {
229 Some(b) => (b.min(top), b.max(top)),
230 None => (0, top),
231 };
232 let col = color_of(i, v);
233 for row in 0..area.height as i64 {
234 let (r0, r1) = (row * 8, row * 8 + 8);
235 let cov_lo = a.max(r0) - r0;
236 let cov_hi = b.min(r1) - r0;
237 if cov_hi <= cov_lo {
238 continue;
239 }
240 let y = area.y + area.height - 1 - row as u16;
241 let Some(cell) = buf.cell_mut((x, y)) else {
242 continue;
243 };
244 let ch = if cov_lo == 0 && cov_hi < 8 {
245 GLYPHS[(cov_hi - 1) as usize]
246 } else if cov_lo > 0 && cov_hi == 8 {
247 '█'
249 } else {
250 '█'
251 };
252 cell.set_char(ch).set_fg(col);
253 }
254 }
255 }
256 SparklineStyle::WinLoss => {
257 let b = self.baseline.unwrap_or(0.0);
258 let mid = area.height / 2;
259 for &(i, v) in &pts {
260 let x = area.x + i as u16;
261 let win = v >= b;
262 let col = if win { self.win_color } else { self.loss_color };
263 if area.height == 1 {
264 if let Some(c) = buf.cell_mut((x, area.y)) {
265 c.set_char(if win { '▀' } else { '▄' }).set_fg(col);
266 }
267 continue;
268 }
269 let (r0, r1) = if win {
271 (0, mid)
272 } else {
273 (area.height - mid, area.height)
274 };
275 for r in r0..r1 {
276 if let Some(c) = buf.cell_mut((x, area.y + r)) {
277 c.set_char('█').set_fg(col);
278 }
279 }
280 if area.height % 2 == 1 {
281 if let Some(c) = buf.cell_mut((x, area.y + mid)) {
282 c.set_char('─').set_fg(darken(col, 0.5));
283 }
284 }
285 }
286 }
287 SparklineStyle::Line | SparklineStyle::Area => {
288 if self.style == SparklineStyle::Area {
289 let levels = area.height as f64 * 8.0;
290 for &(i, v) in &pts {
291 let x = area.x + i as u16;
292 let top = (norm(v) * levels).round() as i64;
293 let dim = darken(color_of(i, v), 0.6);
294 for row in 0..area.height as i64 {
295 let cov = top - row * 8;
296 if cov <= 0 {
297 break;
298 }
299 let y = area.y + area.height - 1 - row as u16;
300 if let Some(cell) = buf.cell_mut((x, y)) {
301 if cov >= 8 {
302 cell.set_char(' ').set_bg(dim);
303 } else {
304 cell.set_char(GLYPHS[(cov - 1) as usize]).set_fg(dim);
305 }
306 }
307 }
308 }
309 }
310 let mut cv = Canvas::new(area.width, area.height, self.marker);
311 let pw = cv.px_w();
312 let ph = cv.px_h();
313 let pos = |i: usize, v: f64| {
314 (
315 (i as i32 * self.marker.resolution().0 as i32).min(pw - 1),
316 ph - 1 - (norm(v) * (ph - 1) as f64).round() as i32,
317 )
318 };
319 let mut prev: Option<(i32, i32)> = None;
320 for &(i, v) in &pts {
321 let p = pos(i, v);
322 let col = color_of(i, v);
323 match prev {
324 Some(q) => cv.line(q.0, q.1, p.0, p.1, col),
325 None => cv.set(p.0, p.1, col),
326 }
327 prev = Some(p);
328 }
329 cv.render(buf, area);
330 }
331 }
332 }
333}
334
335impl Sparkline<'_> {
336 fn render_into(&self, area: Rect, buf: &mut Buffer) {
337 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
338 self.draw(inner, buf);
339 }
340}
341
342widget_impls!(Sparkline<'_>);
343
344#[cfg(feature = "theme")]
345impl<'a> tui_nuances::Themed for Sparkline<'a> {
346 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
347 self.theme(theme)
348 }
349}
350
351#[cfg(test)]
352mod tests {
353 use super::*;
354 use ratatui::widgets::Widget;
355
356 fn sym(buf: &Buffer, x: u16, y: u16) -> String {
357 buf[(x, y)].symbol().to_string()
358 }
359
360 #[test]
361 fn single_row_levels() {
362 let area = Rect::new(0, 0, 3, 1);
363 let mut buf = Buffer::empty(area);
364 Sparkline::new([0.0, 4.0, 8.0]).render(area, &mut buf);
365 assert_eq!(sym(&buf, 0, 0), "▁");
366 assert_eq!(sym(&buf, 2, 0), "█");
367 }
368
369 #[test]
370 fn highlights_and_gradient() {
371 let area = Rect::new(0, 0, 3, 1);
372 let mut buf = Buffer::empty(area);
373 Sparkline::new([1.0, 2.0, 3.0])
374 .highlight_last(Color::Red)
375 .highlight_min(Color::Blue)
376 .render(area, &mut buf);
377 assert_eq!(buf[(2, 0)].fg, Color::Red);
378 assert_eq!(buf[(0, 0)].fg, Color::Blue);
379 }
380
381 #[test]
382 fn tall_bars_fill_rows() {
383 let area = Rect::new(0, 0, 2, 3);
384 let mut buf = Buffer::empty(area);
385 Sparkline::new([0.0, 10.0]).min(0.0).render(area, &mut buf);
386 assert_eq!(sym(&buf, 1, 0), "█");
387 assert_eq!(sym(&buf, 1, 2), "█");
388 }
389
390 #[test]
391 fn line_style_and_degenerate() {
392 let area = Rect::new(0, 0, 5, 2);
393 let mut buf = Buffer::empty(area);
394 Sparkline::new([1.0, 2.0, 1.0])
395 .style(SparklineStyle::Line)
396 .render(area, &mut buf);
397 Sparkline::new([f64::NAN, 1.0, f64::INFINITY]).render(area, &mut buf);
398 Sparkline::new(Vec::new()).render(area, &mut buf);
399 Sparkline::new([1.0]).render(Rect::new(0, 0, 0, 0), &mut buf);
400 Sparkline::new([5.0, 5.0]).render(area, &mut buf);
401 }
402
403 #[test]
404 fn area_fills_below_line_and_winloss_splits() {
405 let area = Rect::new(0, 0, 3, 3);
406 let mut buf = Buffer::empty(area);
407 Sparkline::new([10.0, 10.0, 10.0])
408 .min(0.0)
409 .style(SparklineStyle::Area)
410 .render(area, &mut buf);
411 assert_ne!(buf[(1, 2)].bg, Color::Reset); let mut buf = Buffer::empty(Rect::new(0, 0, 2, 4));
413 Sparkline::new([1.0, -1.0])
414 .style(SparklineStyle::WinLoss)
415 .render(Rect::new(0, 0, 2, 4), &mut buf);
416 assert_eq!(sym(&buf, 0, 0), "█");
417 assert_eq!(sym(&buf, 0, 3), " ");
418 assert_eq!(sym(&buf, 1, 3), "█");
419 assert_eq!(buf[(1, 3)].fg, Color::Red);
420 }
421
422 #[test]
423 fn smoothing_averages() {
424 let area = Rect::new(0, 0, 3, 1);
425 let mut buf = Buffer::empty(area);
426 Sparkline::new([0.0, 8.0, 0.0, 8.0])
427 .smooth(2)
428 .min(0.0)
429 .max(8.0)
430 .render(area, &mut buf);
431 assert_eq!(sym(&buf, 2, 0), "▄"); }
433
434 #[test]
435 fn keeps_newest_when_narrow() {
436 let area = Rect::new(0, 0, 2, 1);
437 let mut buf = Buffer::empty(area);
438 Sparkline::new([8.0, 0.0, 8.0])
439 .min(0.0)
440 .max(8.0)
441 .render(area, &mut buf);
442 assert_eq!(sym(&buf, 1, 0), "█");
443 assert_eq!(sym(&buf, 0, 0), "▁");
444 }
445}