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)]
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 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 min: f64
92 );
93 opt_setter!(
94 max: f64
96 );
97 opt_setter!(
98 baseline: f64
100 );
101 setter!(
102 style: SparklineStyle
104 );
105 opt_setter!(
106 color: Color
108 );
109 theme_setter!(
110 theme
113 );
114 setter!(
115 theme_gradient: bool
118 );
119 base_style_setter!(base);
120 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_last => last_color: Color
128 );
129 opt_setter!(
130 highlight_min => min_color: Color
132 );
133 opt_setter!(
134 highlight_max => max_color: Color
136 );
137 setter!(
138 marker: Marker
140 );
141
142 setter!(
143 smooth: usize
145 );
146 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 let base = self
202 .color
203 .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Cyan, |t| t.accent));
204 let themed: Vec<Color> = match (&self.theme, self.theme_gradient) {
205 (Some(t), true) if self.gradient.is_empty() => {
206 let g = t.gradient();
207 (0..5).map(|i| g.color_at(i as f64 / 4.0)).collect()
208 }
209 _ => Vec::new(),
210 };
211 let grad = if self.gradient.is_empty() {
212 &themed
213 } else {
214 &self.gradient
215 };
216 let color_of = |i: usize, v: f64| {
217 let mut c = base;
218 if !grad.is_empty() {
219 let k = (norm(v) * (grad.len() - 1) as f64).round() as usize;
220 c = grad[k.min(grad.len() - 1)];
221 }
222 if v == dmax {
223 c = self.max_color.unwrap_or(c);
224 }
225 if v == dmin {
226 c = self.min_color.unwrap_or(c);
227 }
228 if Some(i) == n_last {
229 c = self.last_color.unwrap_or(c);
230 }
231 c
232 };
233 match self.style {
234 SparklineStyle::Bar => {
235 let levels = area.height as f64 * 8.0;
236 let base = self.baseline.map(norm).map(|b| (b * levels).round() as i64);
237 for &(i, v) in &pts {
238 let x = area.x + i as u16;
239 let top = ((norm(v) * levels).round() as i64).max(1);
240 let (a, b) = match base {
241 Some(b) => (b.min(top), b.max(top)),
242 None => (0, top),
243 };
244 let col = color_of(i, v);
245 for row in 0..area.height as i64 {
246 let (r0, r1) = (row * 8, row * 8 + 8);
247 let cov_lo = a.max(r0) - r0;
248 let cov_hi = b.min(r1) - r0;
249 if cov_hi <= cov_lo {
250 continue;
251 }
252 let y = area.y + area.height - 1 - row as u16;
253 let Some(cell) = buf.cell_mut((x, y)) else {
254 continue;
255 };
256 let ch = if cov_lo == 0 && cov_hi < 8 {
257 GLYPHS[(cov_hi - 1) as usize]
258 } else if cov_lo > 0 && cov_hi == 8 {
259 '█'
261 } else {
262 '█'
263 };
264 cell.set_char(ch).set_fg(col);
265 }
266 }
267 }
268 SparklineStyle::WinLoss => {
269 let b = self.baseline.unwrap_or(0.0);
270 let mid = area.height / 2;
271 for &(i, v) in &pts {
272 let x = area.x + i as u16;
273 let win = v >= b;
274 let col = if win { self.win_color } else { self.loss_color };
275 if area.height == 1 {
276 if let Some(c) = buf.cell_mut((x, area.y)) {
277 c.set_char(if win { '▀' } else { '▄' }).set_fg(col);
278 }
279 continue;
280 }
281 let (r0, r1) = if win {
283 (0, mid)
284 } else {
285 (area.height - mid, area.height)
286 };
287 for r in r0..r1 {
288 if let Some(c) = buf.cell_mut((x, area.y + r)) {
289 c.set_char('█').set_fg(col);
290 }
291 }
292 if area.height % 2 == 1 {
293 if let Some(c) = buf.cell_mut((x, area.y + mid)) {
294 c.set_char('─').set_fg(darken(col, 0.5));
295 }
296 }
297 }
298 }
299 SparklineStyle::Line | SparklineStyle::Area => {
300 if self.style == SparklineStyle::Area {
301 let levels = area.height as f64 * 8.0;
302 for &(i, v) in &pts {
303 let x = area.x + i as u16;
304 let top = (norm(v) * levels).round() as i64;
305 let dim = darken(color_of(i, v), 0.6);
306 for row in 0..area.height as i64 {
307 let cov = top - row * 8;
308 if cov <= 0 {
309 break;
310 }
311 let y = area.y + area.height - 1 - row as u16;
312 if let Some(cell) = buf.cell_mut((x, y)) {
313 if cov >= 8 {
314 cell.set_char(' ').set_bg(dim);
315 } else {
316 cell.set_char(GLYPHS[(cov - 1) as usize]).set_fg(dim);
317 }
318 }
319 }
320 }
321 }
322 let mut cv = Canvas::new(area.width, area.height, self.marker);
323 let pw = cv.px_w();
324 let ph = cv.px_h();
325 let pos = |i: usize, v: f64| {
326 (
327 (i as i32 * self.marker.resolution().0 as i32).min(pw - 1),
328 ph - 1 - (norm(v) * (ph - 1) as f64).round() as i32,
329 )
330 };
331 let mut prev: Option<(i32, i32)> = None;
332 for &(i, v) in &pts {
333 let p = pos(i, v);
334 let col = color_of(i, v);
335 match prev {
336 Some(q) => cv.line(q.0, q.1, p.0, p.1, col),
337 None => cv.set(p.0, p.1, col),
338 }
339 prev = Some(p);
340 }
341 cv.render(buf, area);
342 }
343 }
344 }
345}
346
347impl Sparkline<'_> {
348 fn render_into(&self, area: Rect, buf: &mut Buffer) {
349 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
350 self.draw(inner, buf);
351 }
352}
353
354widget_impls!(Sparkline<'_>);
355
356#[cfg(feature = "theme")]
357impl<'a> tui_nuances::Themed for Sparkline<'a> {
358 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
359 self.theme(theme)
360 }
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366 use ratatui::widgets::Widget;
367
368 fn sym(buf: &Buffer, x: u16, y: u16) -> String {
369 buf[(x, y)].symbol().to_string()
370 }
371
372 #[test]
373 fn single_row_levels() {
374 let area = Rect::new(0, 0, 3, 1);
375 let mut buf = Buffer::empty(area);
376 Sparkline::new([0.0, 4.0, 8.0]).render(area, &mut buf);
377 assert_eq!(sym(&buf, 0, 0), "▁");
378 assert_eq!(sym(&buf, 2, 0), "█");
379 }
380
381 #[test]
382 fn highlights_and_gradient() {
383 let area = Rect::new(0, 0, 3, 1);
384 let mut buf = Buffer::empty(area);
385 Sparkline::new([1.0, 2.0, 3.0])
386 .highlight_last(Color::Red)
387 .highlight_min(Color::Blue)
388 .render(area, &mut buf);
389 assert_eq!(buf[(2, 0)].fg, Color::Red);
390 assert_eq!(buf[(0, 0)].fg, Color::Blue);
391 }
392
393 #[test]
394 fn tall_bars_fill_rows() {
395 let area = Rect::new(0, 0, 2, 3);
396 let mut buf = Buffer::empty(area);
397 Sparkline::new([0.0, 10.0]).min(0.0).render(area, &mut buf);
398 assert_eq!(sym(&buf, 1, 0), "█");
399 assert_eq!(sym(&buf, 1, 2), "█");
400 }
401
402 #[test]
403 fn line_style_and_degenerate() {
404 let area = Rect::new(0, 0, 5, 2);
405 let mut buf = Buffer::empty(area);
406 Sparkline::new([1.0, 2.0, 1.0])
407 .style(SparklineStyle::Line)
408 .render(area, &mut buf);
409 Sparkline::new([f64::NAN, 1.0, f64::INFINITY]).render(area, &mut buf);
410 Sparkline::new(Vec::new()).render(area, &mut buf);
411 Sparkline::new([1.0]).render(Rect::new(0, 0, 0, 0), &mut buf);
412 Sparkline::new([5.0, 5.0]).render(area, &mut buf);
413 }
414
415 #[test]
416 fn area_fills_below_line_and_winloss_splits() {
417 let area = Rect::new(0, 0, 3, 3);
418 let mut buf = Buffer::empty(area);
419 Sparkline::new([10.0, 10.0, 10.0])
420 .min(0.0)
421 .style(SparklineStyle::Area)
422 .render(area, &mut buf);
423 assert_ne!(buf[(1, 2)].bg, Color::Reset); let mut buf = Buffer::empty(Rect::new(0, 0, 2, 4));
425 Sparkline::new([1.0, -1.0])
426 .style(SparklineStyle::WinLoss)
427 .render(Rect::new(0, 0, 2, 4), &mut buf);
428 assert_eq!(sym(&buf, 0, 0), "█");
429 assert_eq!(sym(&buf, 0, 3), " ");
430 assert_eq!(sym(&buf, 1, 3), "█");
431 assert_eq!(buf[(1, 3)].fg, Color::Red);
432 }
433
434 #[test]
435 fn smoothing_averages() {
436 let area = Rect::new(0, 0, 3, 1);
437 let mut buf = Buffer::empty(area);
438 Sparkline::new([0.0, 8.0, 0.0, 8.0])
439 .smooth(2)
440 .min(0.0)
441 .max(8.0)
442 .render(area, &mut buf);
443 assert_eq!(sym(&buf, 2, 0), "▄"); }
445
446 #[test]
447 fn keeps_newest_when_narrow() {
448 let area = Rect::new(0, 0, 2, 1);
449 let mut buf = Buffer::empty(area);
450 Sparkline::new([8.0, 0.0, 8.0])
451 .min(0.0)
452 .max(8.0)
453 .render(area, &mut buf);
454 assert_eq!(sym(&buf, 1, 0), "█");
455 assert_eq!(sym(&buf, 0, 0), "▁");
456 }
457}