Skip to main content

gradient_bar/
gradient.rs

1use std::fmt::{Display, Write as _};
2
3/// A curated set of smooth, true-color progress gradients.
4///
5/// Each variant interpolates a *linear* ramp between a start and an end RGB
6/// color across the bar, giving a gradual multi-stop feel rather than the flat
7/// two-tone `wide_bar`. Works on any terminal with 24-bit color support (the
8/// default on modern terminals); degraded gracefully elsewhere.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
10pub enum Gradient {
11    /// Deep blue -> ice cyan. The Enkryptit signature look.
12    #[default]
13    Ocean,
14
15    /// Violet -> magenta.
16    Violet,
17
18    /// Warm orange -> gold.
19    Sunset,
20
21    /// Aqua green -> mint.
22    Mint,
23
24    /// Amber -> Light Red (danger / critical ops).
25    Ember,
26
27    /// Cool white -> pale blue.
28    Ice,
29
30    /// Blue / light cyan green -> light purple
31    Aurora,
32
33    /// Cyan -> light blue / purple
34    Neon,
35
36    /// Pink -> light Coral
37    Rose,
38
39    /// Green -> light green
40    Forest,
41
42    /// Dark blue -> light purple
43    Midnight,
44
45    /// A gray-blue -> soft lavender.
46    Twilight,
47
48    /// Deep coral -> soft peach.
49    Coral,
50}
51
52impl Gradient {
53    /// The `(start, end)` RGB stops for this gradient.
54    pub fn stops(self) -> ((u8, u8, u8), (u8, u8, u8)) {
55        match self {
56            Gradient::Ocean => ((8, 150, 255), (150, 235, 255)),
57            Gradient::Violet => ((140, 60, 255), (255, 90, 220)),
58            Gradient::Sunset => ((255, 120, 60), (255, 220, 90)),
59            Gradient::Mint => ((40, 200, 150), (150, 245, 190)),
60            Gradient::Ember => ((255, 120, 30), (220, 40, 60)),
61            Gradient::Ice => ((150, 200, 255), (245, 250, 255)),
62            Gradient::Aurora => ((80, 255, 210), (170, 80, 255)),
63            Gradient::Neon => ((0, 255, 220), (100, 120, 255)),
64            Gradient::Rose => ((255, 120, 180), (255, 170, 130)),
65            Gradient::Forest => ((30, 150, 90), (180, 220, 80)),
66            Gradient::Twilight => ((25, 65, 130), (155, 135, 210)),
67            Gradient::Midnight => ((20, 30, 80), (100, 70, 180)),
68            Gradient::Coral => ((220, 80, 85), (255, 175, 135)),
69        }
70    }
71
72    /// Render a `width`-column true-color gradient bar reflecting `fraction`
73    /// (0.0 → 1.0) of completed work.
74    pub fn render(self, fraction: f32, width: usize) -> String {
75        let ((r0, g0, b0), (r1, g1, b1)) = self.stops();
76        let filled = (fraction.clamp(0.0, 1.0) * width as f32).round() as usize;
77
78        let mut out = String::with_capacity(width * 16 + 8);
79
80        for i in 0..filled {
81            let t = if width > 1 {
82                i as f32 / (width - 1) as f32
83            } else {
84                0.0
85            };
86            let r = r0 as f32 + (r1 as f32 - r0 as f32) * t;
87            let g = g0 as f32 + (g1 as f32 - g0 as f32) * t;
88            let b = b0 as f32 + (b1 as f32 - b0 as f32) * t;
89            let _ = write!(out, "\x1b[38;2;{};{};{}m█", r as u8, g as u8, b as u8);
90        }
91
92        if filled < width {
93            let _ = write!(out, "\x1b[38;2;58;66;82m"); // dim slate for the remainder
94            for _ in filled..width {
95                out.push('·');
96            }
97        }
98
99        out.push_str("\x1b[0m");
100        out
101    }
102
103    /// name for the gradient (used in `Debug`/messages).
104    pub fn name(self) -> &'static str {
105        match self {
106            Gradient::Ocean => "Ocean",
107            Gradient::Violet => "Violet",
108            Gradient::Sunset => "Sunset",
109            Gradient::Mint => "Mint",
110            Gradient::Ember => "Ember",
111            Gradient::Ice => "Ice",
112            Gradient::Aurora => "Aurora",
113            Gradient::Twilight => "Twilight",
114            Gradient::Forest => "Forest",
115            Gradient::Midnight => "Midnight",
116            Gradient::Neon => "Neon",
117            Gradient::Rose => "Rose",
118            Gradient::Coral => "Coral",
119        }
120    }
121}
122
123impl Display for Gradient {
124    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125        write!(f, "{}", self.name())
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[test]
134    fn name_returns_correct_strings() {
135        assert_eq!(Gradient::Ocean.name(), "Ocean");
136        assert_eq!(Gradient::Violet.name(), "Violet");
137        assert_eq!(Gradient::Sunset.name(), "Sunset");
138        assert_eq!(Gradient::Mint.name(), "Mint");
139        assert_eq!(Gradient::Ember.name(), "Ember");
140        assert_eq!(Gradient::Ice.name(), "Ice");
141        assert_eq!(Gradient::Aurora.name(), "Aurora");
142        assert_eq!(Gradient::Neon.name(), "Neon");
143        assert_eq!(Gradient::Rose.name(), "Rose");
144        assert_eq!(Gradient::Forest.name(), "Forest");
145        assert_eq!(Gradient::Midnight.name(), "Midnight");
146        assert_eq!(Gradient::Twilight.name(), "Twilight");
147        assert_eq!(Gradient::Coral.name(), "Coral");
148    }
149
150    #[test]
151    fn stops_are_distinct_per_gradient() {
152        let seen: Vec<_> = [
153            Gradient::Ocean,
154            Gradient::Violet,
155            Gradient::Sunset,
156            Gradient::Mint,
157            Gradient::Ember,
158            Gradient::Ice,
159            Gradient::Aurora,
160            Gradient::Neon,
161            Gradient::Rose,
162            Gradient::Forest,
163            Gradient::Midnight,
164            Gradient::Twilight,
165            Gradient::Coral,
166        ]
167        .iter()
168        .map(|g| g.stops())
169        .collect();
170        for (i, a) in seen.iter().enumerate() {
171            for (j, b) in seen.iter().enumerate() {
172                if i != j {
173                    assert_ne!(a, b, "gradients {i} and {j} should have different stops");
174                }
175            }
176        }
177    }
178
179    #[test]
180    fn render_at_zero_is_all_dots() {
181        let out = Gradient::Ocean.render(0.0, 20);
182        assert!(out.contains("·"), "expected dots at 0%: {out}");
183        assert!(
184            !out.contains("█"),
185            "should have no filled blocks at 0%: {out}"
186        );
187    }
188
189    #[test]
190    fn render_at_one_is_all_filled() {
191        let out = Gradient::Ocean.render(1.0, 20);
192        assert!(out.contains("█"), "expected filled blocks at 100%: {out}");
193        let dot_count = out.matches('·').count();
194        assert_eq!(dot_count, 0, "should have no dots at 100%: {out}");
195    }
196
197    #[test]
198    fn render_halfway_approximately_half() {
199        let width = 20;
200        let out = Gradient::Sunset.render(0.5, width);
201        let filled = out.matches('█').count();
202        let dots = out.matches('·').count();
203        assert_eq!(filled + dots, width, "total chars should equal width");
204        assert!(
205            (filled as i32 - dots as i32).unsigned_abs() <= 2,
206            "filled ({filled}) and dots ({dots}) should be roughly equal"
207        );
208    }
209
210    #[test]
211    fn render_width_one() {
212        let out_zero = Gradient::Violet.render(0.0, 1);
213        assert!(out_zero.contains('·'));
214
215        let out_one = Gradient::Violet.render(1.0, 1);
216        assert!(out_one.contains('█'));
217    }
218
219    #[test]
220    fn render_clamps_above_one() {
221        let out = Gradient::Mint.render(1.5, 10);
222        let filled = out.matches('█').count();
223        assert_eq!(filled, 10, "fraction > 1.0 should clamp to full bar");
224    }
225
226    #[test]
227    fn render_clamps_below_zero() {
228        let out = Gradient::Ember.render(-0.5, 10);
229        let filled = out.matches('█').count();
230        assert_eq!(filled, 0, "fraction < 0.0 should clamp to empty bar");
231    }
232
233    #[test]
234    fn render_contains_ansi_reset() {
235        let out = Gradient::Ice.render(0.5, 10);
236        assert!(
237            out.ends_with("\x1b[0m"),
238            "output should end with ANSI reset"
239        );
240    }
241
242    #[test]
243    fn default_is_ocean() {
244        assert_eq!(Gradient::default(), Gradient::Ocean);
245    }
246
247    #[test]
248    fn display_formats_with_backticks() {
249        for grad in [
250            Gradient::Ocean,
251            Gradient::Violet,
252            Gradient::Sunset,
253            Gradient::Mint,
254            Gradient::Ember,
255            Gradient::Ice,
256            Gradient::Aurora,
257            Gradient::Neon,
258            Gradient::Rose,
259            Gradient::Forest,
260            Gradient::Midnight,
261            Gradient::Twilight,
262            Gradient::Coral,
263        ] {
264            let expected = grad.name().to_string();
265            assert_eq!(format!("{grad}"), expected, "Display for {grad:?}");
266        }
267    }
268
269    #[test]
270    fn render_each_variant_does_not_panic() {
271        for grad in [
272            Gradient::Ocean,
273            Gradient::Violet,
274            Gradient::Sunset,
275            Gradient::Mint,
276            Gradient::Ember,
277            Gradient::Ice,
278            Gradient::Aurora,
279            Gradient::Neon,
280            Gradient::Rose,
281            Gradient::Forest,
282            Gradient::Midnight,
283            Gradient::Twilight,
284            Gradient::Coral,
285        ] {
286            grad.render(0.0, 0);
287            grad.render(0.33, 30);
288            grad.render(1.0, 1);
289        }
290    }
291}