use core::fmt::Write as _;
use retroglyph_core::{Color, Rect, Style};
use super::{Widget, bar};
use crate::Surface;
use crate::Theme;
#[derive(Clone, Copy, Debug)]
pub struct Gauge<'a> {
label: &'a str,
ratio: f32,
label_style: Style,
}
impl<'a> Gauge<'a> {
#[must_use]
pub fn new(label: &'a str, ratio: f32) -> Self {
Self {
label,
ratio,
label_style: bar::default_label_style(),
}
}
#[must_use]
pub const fn label_style(mut self, style: Style) -> Self {
self.label_style = style;
self
}
#[must_use]
pub fn theme(self, theme: Theme) -> Self {
self.theme_on(theme, theme.panel_bg)
}
#[must_use]
pub fn theme_on(mut self, theme: Theme, bg: Color) -> Self {
self.label_style = Style::new().fg(theme.dim).bg(bg);
self
}
}
impl Widget for Gauge<'_> {
fn render(&self, area: Rect, surface: &mut Surface<'_>) {
let ratio = self.ratio.clamp(0.0, 1.0);
let mut pct = bar::ReadoutBuf::<4>::new();
#[allow(clippy::cast_possible_truncation)]
let pct_value = (ratio * 100.0).round() as i32;
let _ = write!(pct, "{pct_value:>3}%");
bar::render(
surface,
area,
self.label,
self.label_style,
ratio,
pct.as_str(),
);
}
}
#[cfg(test)]
mod tests {
use retroglyph_core::{Grid, Pos};
use super::*;
#[test]
fn label_bar_and_percentage_readout() {
let area = Rect::new(0, 0, 20, 1);
let mut grid = Grid::new(20, 1);
Gauge::new("H", 0.5).render(area, &mut Surface::new(&mut grid, area, 0));
assert_eq!(grid[Pos::new(2, 0)].glyph(), '█'); assert_eq!(grid[Pos::new(19, 0)].glyph(), '%'); }
#[test]
fn label_style_is_configurable() {
use retroglyph_core::Color;
let area = Rect::new(0, 0, 20, 1);
let mut grid = Grid::new(20, 1);
Gauge::new("H", 0.5)
.label_style(Style::new().fg(Color::WHITE))
.render(area, &mut Surface::new(&mut grid, area, 0));
assert_eq!(grid[Pos::new(0, 0)].style().foreground(), Color::WHITE);
}
#[test]
fn theme_maps_dim_role_onto_label_style() {
let area = Rect::new(0, 0, 20, 1);
let mut grid = Grid::new(20, 1);
Gauge::new("H", 0.5)
.theme(Theme::DARK)
.render(area, &mut Surface::new(&mut grid, area, 0));
assert_eq!(grid[Pos::new(0, 0)].style().foreground(), Theme::DARK.dim);
assert_eq!(
grid[Pos::new(0, 0)].style().background(),
Theme::DARK.panel_bg
);
}
#[test]
fn theme_on_uses_the_given_backdrop_instead_of_panel_bg() {
use retroglyph_core::Color;
let area = Rect::new(0, 0, 20, 1);
let mut grid = Grid::new(20, 1);
Gauge::new("H", 0.5)
.theme_on(Theme::DARK, Color::Default)
.render(area, &mut Surface::new(&mut grid, area, 0));
assert_eq!(grid[Pos::new(0, 0)].style().foreground(), Theme::DARK.dim);
assert_eq!(grid[Pos::new(0, 0)].style().background(), Color::Default);
}
}