Skip to main content

gradient_bar/
style.rs

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