use crate::buffer::Buffer;
use crate::layout::Rect;
use crate::style::Style;
use crate::widgets::{Block, Widget};
const BARS: [char; 9] = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
#[derive(Debug, Default, Clone)]
pub struct Sparkline<'a> {
block: Option<Block<'a>>,
data: &'a [u64],
max: Option<u64>,
style: Style,
}
impl<'a> Sparkline<'a> {
pub fn data(data: &'a [u64]) -> Sparkline<'a> {
Sparkline {
block: None,
data,
max: None,
style: Style::default(),
}
}
pub fn block(mut self, block: Block<'a>) -> Sparkline<'a> {
self.block = Some(block);
self
}
pub fn max(mut self, max: u64) -> Sparkline<'a> {
self.max = Some(max);
self
}
pub fn style(mut self, style: Style) -> Sparkline<'a> {
self.style = style;
self
}
}
impl<'a> Widget for Sparkline<'a> {
fn render(mut self, area: Rect, buf: &mut Buffer) {
let area = if let Some(block) = self.block.take() {
let inner = block.inner(area);
block.render(area, buf);
inner
} else {
area
};
if area.area() == 0 {
return;
}
buf.set_style(area, self.style);
let width = area.width as usize;
let window = if self.data.len() > width {
&self.data[self.data.len() - width..]
} else {
self.data
};
let max = self.max.unwrap_or_else(|| window.iter().copied().max().unwrap_or(0)).max(1);
let offset = area.width.saturating_sub(window.len() as u16);
for (i, &value) in window.iter().enumerate() {
let x = area.x + offset + i as u16;
let level = ((value.min(max) as f64 / max as f64) * 8.0).round() as usize;
let ch = BARS[level.min(8)];
buf.get_mut(x, area.y).set_char(ch).set_style(self.style);
}
}
}