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