Skip to main content

tui_chart/
util.rs

1//! Numeric helpers: "nice" tick generation and number formatting.
2
3/// Round a raw step up to a "nice" value (1, 2, 5 × 10ⁿ).
4pub fn nice_step(raw: f64) -> f64 {
5    if !raw.is_finite() || raw <= 0.0 {
6        return 1.0;
7    }
8    let exp = raw.log10().floor();
9    let base = 10f64.powf(exp);
10    let f = raw / base;
11    let nf = if f <= 1.0 {
12        1.0
13    } else if f <= 2.0 {
14        2.0
15    } else if f <= 2.5 {
16        2.5
17    } else if f <= 5.0 {
18        5.0
19    } else {
20        10.0
21    };
22    nf * base
23}
24
25/// Generate roughly `count` nicely spaced tick values inside `[min, max]`.
26pub fn nice_ticks(min: f64, max: f64, count: usize) -> Vec<f64> {
27    if !min.is_finite() || !max.is_finite() || max <= min {
28        return if min.is_finite() { vec![min] } else { vec![] };
29    }
30    let count = count.max(2);
31    let step = nice_step((max - min) / (count - 1) as f64);
32    let mut v = (min / step).ceil();
33    let mut out = Vec::new();
34    while v * step <= max + step * 1e-9 && out.len() < 1000 {
35        out.push(v * step);
36        v += 1.0;
37    }
38    out
39}
40
41/// Expand `[min, max]` outward to the nearest "nice" tick multiples.
42pub fn nice_bounds(min: f64, max: f64, count: usize) -> (f64, f64) {
43    if !min.is_finite() || !max.is_finite() {
44        return (0.0, 1.0);
45    }
46    if max <= min {
47        return (min - 1.0, max + 1.0);
48    }
49    let step = nice_step((max - min) / (count.max(2) - 1) as f64);
50    ((min / step).floor() * step, (max / step).ceil() * step)
51}
52
53/// Step between the first two ticks (or 1.0).
54pub fn tick_step(ticks: &[f64]) -> f64 {
55    if ticks.len() >= 2 {
56        ticks[1] - ticks[0]
57    } else {
58        1.0
59    }
60}
61
62/// Format a tick value with just enough decimals for the given step.
63pub fn format_tick(v: f64, step: f64) -> String {
64    let decimals = if !step.is_finite() || step <= 0.0 {
65        0
66    } else {
67        (0..=8usize)
68            .find(|d| {
69                let x = step * 10f64.powi(*d as i32);
70                (x - x.round()).abs() < 1e-6 * x.max(1.0)
71            })
72            .unwrap_or(8)
73    };
74    let s = format!("{v:.decimals$}");
75    if s.starts_with('-') && s[1..].chars().all(|c| c == '0' || c == '.') {
76        s[1..].to_string()
77    } else {
78        s
79    }
80}
81
82/// Compact human format: `1.5k`, `2.3M`, `4B`.
83pub fn format_compact(v: f64) -> String {
84    let a = v.abs();
85    let (d, suffix) = if a >= 1e9 {
86        (1e9, "B")
87    } else if a >= 1e6 {
88        (1e6, "M")
89    } else if a >= 1e3 {
90        (1e3, "k")
91    } else {
92        (1.0, "")
93    };
94    let x = v / d;
95    if suffix.is_empty() {
96        if (x - x.round()).abs() < 1e-9 {
97            format!("{}", x.round() as i64)
98        } else {
99            format!("{x:.2}")
100        }
101    } else if (x - x.round()).abs() < 0.05 {
102        format!("{}{suffix}", x.round() as i64)
103    } else {
104        format!("{x:.1}{suffix}")
105    }
106}
107
108/// Approximate RGB of a terminal color (named colors use common xterm values).
109pub fn to_rgb(c: ratatui::style::Color) -> (u8, u8, u8) {
110    use ratatui::style::Color::*;
111    match c {
112        Rgb(r, g, b) => (r, g, b),
113        Black => (0, 0, 0),
114        Red => (205, 49, 49),
115        Green => (13, 188, 121),
116        Yellow => (229, 229, 16),
117        Blue => (36, 114, 200),
118        Magenta => (188, 63, 188),
119        Cyan => (17, 168, 205),
120        Gray => (229, 229, 229),
121        DarkGray => (102, 102, 102),
122        LightRed => (241, 76, 76),
123        LightGreen => (35, 209, 139),
124        LightYellow => (245, 245, 67),
125        LightBlue => (59, 142, 234),
126        LightMagenta => (214, 112, 214),
127        LightCyan => (41, 184, 219),
128        White => (255, 255, 255),
129        Reset | Indexed(_) => (150, 150, 150),
130    }
131}
132
133/// Mix `a` toward `b` by `t` (0 = `a`, 1 = `b`); the result is always `Rgb`.
134pub fn mix(a: ratatui::style::Color, b: ratatui::style::Color, t: f64) -> ratatui::style::Color {
135    let (a, b) = (to_rgb(a), to_rgb(b));
136    let t = t.clamp(0.0, 1.0);
137    let f = |x: u8, y: u8| (x as f64 + (y as f64 - x as f64) * t).round() as u8;
138    ratatui::style::Color::Rgb(f(a.0, b.0), f(a.1, b.1), f(a.2, b.2))
139}
140
141/// Darken a color toward black by `amount` (0..=1); used for unfilled tracks.
142pub fn darken(c: ratatui::style::Color, amount: f64) -> ratatui::style::Color {
143    if amount <= 0.0 {
144        return c; // keep named colors untouched
145    }
146    mix(c, ratatui::style::Color::Rgb(0, 0, 0), amount)
147}
148
149/// Dim (grid/axis) and text styles for a widget's optional theme.
150pub(crate) fn dim_text(
151    theme: &Option<crate::theme::Theme>,
152) -> (ratatui::style::Style, ratatui::style::Style) {
153    use ratatui::style::{Color, Style};
154    let dim = Style::default().fg(theme.as_ref().map_or(Color::DarkGray, |t| t.grid));
155    let text = theme.as_ref().map_or(Style::default(), |t| t.label_style());
156    (dim, text)
157}
158
159/// Color `i` of the theme palette, or of the default palette without a theme.
160pub(crate) fn pick(theme: &Option<crate::theme::Theme>, i: usize) -> ratatui::style::Color {
161    theme
162        .as_ref()
163        .map_or(crate::PALETTE[i % crate::PALETTE.len()], |t| t.color(i))
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn step_is_nice() {
172        assert_eq!(nice_step(0.7), 1.0);
173        assert_eq!(nice_step(1.5), 2.0);
174        assert_eq!(nice_step(2.2), 2.5);
175        assert_eq!(nice_step(3.0), 5.0);
176        assert_eq!(nice_step(7.0), 10.0);
177        assert_eq!(nice_step(0.0), 1.0);
178        assert_eq!(nice_step(f64::NAN), 1.0);
179    }
180
181    #[test]
182    fn ticks_cover_range() {
183        let t = nice_ticks(0.0, 100.0, 5);
184        assert_eq!(t, vec![0.0, 25.0, 50.0, 75.0, 100.0]);
185        let t = nice_ticks(0.0, 1.0, 5);
186        assert_eq!(t.len(), 5);
187        assert!((t[1] - 0.25).abs() < 1e-12);
188    }
189
190    #[test]
191    fn ticks_degenerate() {
192        assert_eq!(nice_ticks(3.0, 3.0, 5), vec![3.0]);
193        assert!(nice_ticks(f64::NAN, 1.0, 5).is_empty());
194    }
195
196    #[test]
197    fn bounds_expand() {
198        let (lo, hi) = nice_bounds(3.2, 97.5, 5);
199        assert!(lo <= 3.2 && hi >= 97.5);
200        assert_eq!(nice_bounds(5.0, 5.0, 5), (4.0, 6.0));
201    }
202
203    #[test]
204    fn tick_formatting() {
205        assert_eq!(format_tick(20.0, 20.0), "20");
206        assert_eq!(format_tick(2.5, 2.5), "2.5");
207        assert_eq!(format_tick(0.25, 0.05), "0.25");
208        assert_eq!(format_tick(-0.0, 0.1), "0.0");
209        assert_eq!(tick_step(&[1.0, 3.0, 5.0]), 2.0);
210        assert_eq!(tick_step(&[1.0]), 1.0);
211    }
212
213    #[test]
214    fn compact_formatting() {
215        assert_eq!(format_compact(999.0), "999");
216        assert_eq!(format_compact(1500.0), "1.5k");
217        assert_eq!(format_compact(2_000_000.0), "2M");
218        assert_eq!(format_compact(3_400_000_000.0), "3.4B");
219        assert_eq!(format_compact(1.25), "1.25");
220    }
221
222    #[test]
223    fn mix_and_darken() {
224        use ratatui::style::Color;
225        assert_eq!(
226            mix(Color::Rgb(0, 0, 0), Color::Rgb(100, 200, 50), 0.5),
227            Color::Rgb(50, 100, 25)
228        );
229        assert_eq!(darken(Color::Rgb(200, 100, 50), 1.0), Color::Rgb(0, 0, 0));
230        assert_eq!(
231            darken(Color::Rgb(200, 100, 50), 0.0),
232            Color::Rgb(200, 100, 50)
233        );
234    }
235}