Skip to main content

retroglyph_ui/widget/
meter.rs

1//! [`Meter`]: a load ratio mapped to a green→yellow→red color.
2use retroglyph_core::color::Color;
3
4/// A load ratio in `0.0..=1.0`, mapped to a green→yellow→red color ramp.
5///
6/// Low load is green, mid load yellow, high load red. Values outside the
7/// range are clamped. Delegates to [`Color::lerp`] (backed by `gem`) rather
8/// than hand-rolling RGB interpolation.
9///
10/// Not a drawing widget: there's no [`Terminal`](retroglyph_core::terminal::Terminal)
11/// involved, just a ratio-to-color mapping, but kept as its own small
12/// struct rather than a free function so [`Gauge`](super::Gauge),
13/// [`StatBar`](super::StatBar), and [`Sparkline`](super::Sparkline) share
14/// one place that owns the ramp.
15///
16/// # Examples
17///
18/// ```
19/// use retroglyph_ui::widget::Meter;
20///
21/// let meter = Meter::new(0.9);
22/// assert_ne!(meter.color(), Meter::new(0.1).color());
23/// ```
24#[derive(Clone, Copy, Debug, PartialEq)]
25pub struct Meter {
26    ratio: f32,
27}
28
29impl Meter {
30    // Ramp endpoints, lerped through YELLOW at the midpoint (see `color`). Picked by eye for a
31    // readable green/amber/red load ramp on a dark background; not measured against any palette.
32    const GREEN: Color = Color::rgb(80, 200, 120);
33    const YELLOW: Color = Color::rgb(220, 200, 90);
34    const RED: Color = Color::rgb(220, 90, 90);
35
36    /// A meter reading `ratio` (clamped to `0.0..=1.0` when colored).
37    #[must_use]
38    pub const fn new(ratio: f32) -> Self {
39        Self { ratio }
40    }
41
42    /// The ramped color for this meter's ratio.
43    #[must_use]
44    pub fn color(self) -> Color {
45        let t = self.ratio.clamp(0.0, 1.0);
46        if t < 0.5 {
47            Color::lerp(Self::GREEN, Self::YELLOW, t * 2.0)
48        } else {
49            Color::lerp(Self::YELLOW, Self::RED, (t - 0.5) * 2.0)
50        }
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn low_load_is_green() {
60        assert_eq!(Meter::new(0.0).color(), Meter::GREEN);
61    }
62
63    #[test]
64    fn mid_load_is_yellow() {
65        assert_eq!(Meter::new(0.5).color(), Meter::YELLOW);
66    }
67
68    #[test]
69    fn high_load_is_red() {
70        assert_eq!(Meter::new(1.0).color(), Meter::RED);
71    }
72
73    #[test]
74    fn out_of_range_ratios_are_clamped() {
75        assert_eq!(Meter::new(-1.0).color(), Meter::GREEN);
76        assert_eq!(Meter::new(2.0).color(), Meter::RED);
77    }
78}