rustom 0.1.0

A library for building rich, stateful terminal user interfaces and dashboards.
Documentation
use crate::buffer::Buffer;
use crate::layout::Rect;
use crate::style::Style;
use crate::widgets::{Block, Widget};

/// Eight levels of vertical fill, from empty to full, used to render each
/// data point at sub-cell resolution.
const BARS: [char; 9] = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];

/// A compact single-row chart, showing the most recent values in `data` as
/// a strip of variable height bars. Only the last `area.width` points are
/// shown, right-aligned, so the most recent value is always closest to the
/// right edge.
#[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
    }

    /// Fixes the value that maps to a full height bar. Defaults to the
    /// largest value present in `data`.
    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);

        // Right align: leave any leftover columns blank on the left.
        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);
        }
    }
}