Skip to main content

gradient_bar/
style.rs

1use crate::gradient::Gradient;
2use indicatif::{ProgressState, ProgressStyle};
3
4/// The look & feel of a [`GradientProgressBar`].
5///
6/// This is the **layout**, independent of the gradient. Pick a layout here, and
7/// pair it with any [`Gradient`] (or none, to keep the classic
8/// two-tone `wide_bar`).
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub enum BarStyle {
11    /// The flagship layout: spinner + message + elapsed + wide bar with
12    /// `bytes/total` + percent + ETA. Best suited to a byte-based workload.
13    Main,
14    /// Compact single-line layout, for tight output or secondary bars.
15    Minified,
16    /// For chunk / step based workloads (e.g. multithreaded splitting). Shows
17    /// `pos/len` as *chunks*.
18    Steps,
19    /// Indeterminate progress (no known total): animates a spinner + message.
20    Spinner,
21    /// Like [`BarStyle::Main`], but cleared from the terminal
22    /// once it finishes (pair with [`GradientProgressBar::finish_and_clear`]).
23    ClearOnFinish,
24}
25
26impl BarStyle {
27    /// Default bar width (in cells) used when rendering a gradient.
28    pub const DEFAULT_GRADIENT_WIDTH: usize = 30;
29
30    /// Build the [`indicatif::ProgressStyle`] for this layout.
31    ///
32    /// When `gradient` is `Some`, the bar is rendered by [`Gradient`]
33    /// (true-color multi-stop). When `None`, the classic two-tone
34    /// `{wide_bar:.cyan/blue}` is used. `width` controls the gradient bar's
35    /// column count.
36    pub fn to_progress_style(&self, gradient: Option<Gradient>, width: usize) -> ProgressStyle {
37        let gname = gradient.map(Gradient::name).unwrap_or("");
38
39        let (bar_key, spinner_color) = match gradient {
40            Some(_) => ("{grad_bar}", "cyan"),
41            None => ("{wide_bar:.cyan/blue}", "green"),
42        };
43
44        let template = match self {
45            BarStyle::Main => format!(
46                "{{spinner:.{spinner_color}}} {{msg}} [{{elapsed_precise}}] [{bar_key}] {{bytes}}/{{total_bytes}} ({{percent}}%) {{eta}}",
47                spinner_color = spinner_color,
48                bar_key = bar_key,
49            ),
50            BarStyle::Minified => format!(
51                "{{spinner:.{spinner_color}}} {{msg}} {{bytes}}/{{total_bytes}} ({{percent}}%) [[{gname}]]",
52                spinner_color = spinner_color,
53                gname = gname,
54            ),
55            BarStyle::Steps => format!(
56                "{{spinner:.cyan}} {{msg}} [{bar_key}] {{pos}}/{{len}} chunks ({{percent}}%) {{elapsed_precise}}",
57                bar_key = bar_key,
58            ),
59            BarStyle::Spinner => "{{spinner:.cyan}} {{msg}}".to_string(),
60            BarStyle::ClearOnFinish => format!(
61                "{{spinner:.{spinner_color}}} {{msg}} [{{elapsed_precise}}] [{bar_key}] {{bytes}}/{{total_bytes}} ({{percent}}%) {{eta}}",
62                spinner_color = spinner_color,
63                bar_key = bar_key,
64            ),
65        };
66
67        let chars = "█▉▊▋▌▍▎▏  ";
68        let tick = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ ";
69
70        let mut style = ProgressStyle::with_template(&template)
71            .expect("the template is valid")
72            .progress_chars(chars)
73            .tick_chars(tick);
74
75        if let Some(gradient) = gradient {
76            // Register a custom renderer for {grad_bar}: a fixed-width,
77            // true-color gradient reflecting the current fraction.
78            let grad = gradient;
79            let w = width.max(1);
80            style = style.with_key(
81                "grad_bar",
82                move |state: &ProgressState, wout: &mut dyn std::fmt::Write| {
83                    let _ = write!(wout, "{}", grad.render(state.fraction(), w));
84                },
85            );
86        }
87
88        style
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95
96    #[test]
97    fn all_styles_build_without_panic() {
98        let gradients = [None, Some(Gradient::Ocean), Some(Gradient::Violet)];
99        for gradient in gradients {
100            for style in [
101                BarStyle::Main,
102                BarStyle::Minified,
103                BarStyle::Steps,
104                BarStyle::Spinner,
105                BarStyle::ClearOnFinish,
106            ] {
107                let _ = style.to_progress_style(gradient, 30);
108            }
109        }
110    }
111
112    #[test]
113    fn default_gradient_width_is_30() {
114        assert_eq!(BarStyle::DEFAULT_GRADIENT_WIDTH, 30);
115    }
116
117    #[test]
118    fn zero_width_builds_without_panic() {
119        for style in [
120            BarStyle::Main,
121            BarStyle::Minified,
122            BarStyle::Steps,
123            BarStyle::Spinner,
124            BarStyle::ClearOnFinish,
125        ] {
126            let _ = style.to_progress_style(Some(Gradient::Ocean), 0);
127            let _ = style.to_progress_style(None, 0);
128        }
129    }
130
131    #[test]
132    fn large_width_builds_without_panic() {
133        let _ = BarStyle::Main.to_progress_style(Some(Gradient::Sunset), 500);
134    }
135
136    #[test]
137    fn bar_style_is_copy_clone_debug() {
138        let s = BarStyle::Main;
139        let s2 = s;
140        let s3 = s;
141        let _ = format!("{:?}", s3);
142        assert_eq!(s, s2);
143    }
144
145    #[test]
146    fn all_variants_are_distinct() {
147        let styles = [
148            BarStyle::Main,
149            BarStyle::Minified,
150            BarStyle::Steps,
151            BarStyle::Spinner,
152            BarStyle::ClearOnFinish,
153        ];
154        for (i, a) in styles.iter().enumerate() {
155            for (j, b) in styles.iter().enumerate() {
156                if i == j {
157                    assert_eq!(a, b);
158                } else {
159                    assert_ne!(a, b);
160                }
161            }
162        }
163    }
164}