Skip to main content

iced_cube/feedback/
progress.rs

1//! Determinate progress bars.
2
3use iced::widget::{column, progress_bar, row, space, text};
4use iced::{Background, Border, Color, Element, Length};
5
6use crate::theme::{Tokens, mix, radius, space as gap, text_size};
7
8/// Colour of the filled part of the bar.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
10pub enum Variant {
11    #[default]
12    Default,
13    Success,
14    Warning,
15    Destructive,
16}
17
18impl Variant {
19    pub const ALL: [Variant; 4] = [
20        Variant::Default,
21        Variant::Success,
22        Variant::Warning,
23        Variant::Destructive,
24    ];
25}
26
27/// Bar thickness.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
29pub enum Size {
30    Sm,
31    #[default]
32    Md,
33    Lg,
34}
35
36impl Size {
37    pub const ALL: [Size; 3] = [Size::Sm, Size::Md, Size::Lg];
38
39    /// Thickness of the bar in logical pixels.
40    pub const fn girth(self) -> f32 {
41        match self {
42            Size::Sm => 4.0,
43            Size::Md => 8.0,
44            Size::Lg => 12.0,
45        }
46    }
47}
48
49/// A progress bar builder. Convert it into an [`Element`] to render.
50#[derive(Debug)]
51pub struct Progress<'a> {
52    value: f32,
53    label: Option<text::Fragment<'a>>,
54    show_percentage: bool,
55    variant: Variant,
56    size: Size,
57    width: Length,
58}
59
60/// Creates a progress bar. `value` runs from 0.0 to 1.0 and is clamped.
61pub fn progress<'a>(value: f32) -> Progress<'a> {
62    Progress {
63        value: clamp(value),
64        label: None,
65        show_percentage: false,
66        variant: Variant::default(),
67        size: Size::default(),
68        width: Length::Fill,
69    }
70}
71
72impl<'a> Progress<'a> {
73    pub fn variant(mut self, variant: Variant) -> Self {
74        self.variant = variant;
75        self
76    }
77
78    pub fn size(mut self, size: Size) -> Self {
79        self.size = size;
80        self
81    }
82
83    /// Shows a caption above the bar.
84    pub fn label(mut self, label: impl text::IntoFragment<'a>) -> Self {
85        self.label = Some(label.into_fragment());
86        self
87    }
88
89    /// Shows the rounded percentage above the bar, on the right.
90    pub fn show_percentage(mut self, show: bool) -> Self {
91        self.show_percentage = show;
92        self
93    }
94
95    /// Overrides the width. Bars fill the available width by default.
96    pub fn width(mut self, width: impl Into<Length>) -> Self {
97        self.width = width.into();
98        self
99    }
100
101    /// The clamped value, from 0.0 to 1.0.
102    pub fn value(&self) -> f32 {
103        self.value
104    }
105}
106
107impl<'a, Message: 'a> From<Progress<'a>> for Element<'a, Message> {
108    fn from(progress: Progress<'a>) -> Self {
109        #[cfg(feature = "icedwright")]
110        {
111            let name = progress.label.clone();
112            let value = format!("{}%", percentage(progress.value));
113            let mut annotated = icedwright_probe::semantic(render(progress))
114                .role(icedwright_probe::role::ProgressIndicator)
115                .value(value)
116                .component("iced_cube::progress");
117            if let Some(name) = name {
118                annotated = annotated.name(name);
119            }
120            annotated.into()
121        }
122        #[cfg(not(feature = "icedwright"))]
123        render(progress)
124    }
125}
126
127fn render<'a, Message: 'a>(progress: Progress<'a>) -> Element<'a, Message> {
128    {
129        let variant = progress.variant;
130        let bar = progress_bar(0.0..=1.0, progress.value)
131            .length(progress.width)
132            .girth(progress.size.girth())
133            .style(move |theme| style(&Tokens::of(theme), variant));
134
135        if progress.label.is_none() && !progress.show_percentage {
136            return bar.into();
137        }
138
139        let muted = |theme: &iced::Theme| text::Style {
140            color: Some(Tokens::of(theme).muted_foreground),
141        };
142        let mut header = row![].width(progress.width);
143        if let Some(label) = progress.label {
144            header = header.push(text(label).size(text_size::SM));
145        }
146        header = header.push(space::horizontal());
147        if progress.show_percentage {
148            header = header.push(
149                text(format!("{}%", percentage(progress.value)))
150                    .size(text_size::SM)
151                    .style(muted),
152            );
153        }
154
155        column![header, bar].spacing(gap::SM).into()
156    }
157}
158
159/// Clamps a value into 0.0..=1.0. NaN becomes 0.0.
160pub fn clamp(value: f32) -> f32 {
161    if value.is_nan() {
162        return 0.0;
163    }
164    value.clamp(0.0, 1.0)
165}
166
167/// A value from 0.0 to 1.0 as a whole percentage.
168pub fn percentage(value: f32) -> u8 {
169    // The clamped value is within 0.0..=100.0, so the cast cannot truncate.
170    (clamp(value) * 100.0).round() as u8
171}
172
173/// Colours of the track and the filled bar.
174#[derive(Debug, Clone, Copy, PartialEq)]
175pub struct Colours {
176    pub track: Color,
177    pub bar: Color,
178}
179
180/// Resolves the colours of a variant.
181pub fn colours(tokens: &Tokens, variant: Variant) -> Colours {
182    let bar = match variant {
183        Variant::Default => tokens.primary,
184        Variant::Success => tokens.success,
185        Variant::Warning => tokens.warning,
186        Variant::Destructive => tokens.destructive,
187    };
188    let track_mix = if tokens.is_dark { 0.2 } else { 0.15 };
189    Colours {
190        track: mix(tokens.background, bar, track_mix),
191        bar,
192    }
193}
194
195/// The iced progress bar style for a variant.
196pub fn style(tokens: &Tokens, variant: Variant) -> progress_bar::Style {
197    let colours = colours(tokens, variant);
198    progress_bar::Style {
199        background: Background::Color(colours.track),
200        bar: Background::Color(colours.bar),
201        border: Border {
202            color: Color::TRANSPARENT,
203            width: 0.0,
204            radius: radius::FULL.into(),
205        },
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212    use crate::theme::{dark, light};
213
214    #[test]
215    fn default_builder_is_medium_default_fill_without_caption() {
216        let p = progress(0.5);
217        assert_eq!(p.variant, Variant::Default);
218        assert_eq!(p.size, Size::Md);
219        assert_eq!(p.width, Length::Fill);
220        assert!(p.label.is_none());
221        assert!(!p.show_percentage);
222    }
223
224    #[test]
225    fn clamp_bounds_values() {
226        assert_eq!(clamp(-0.5), 0.0);
227        assert_eq!(clamp(0.0), 0.0);
228        assert_eq!(clamp(0.42), 0.42);
229        assert_eq!(clamp(1.0), 1.0);
230        assert_eq!(clamp(3.0), 1.0);
231        assert_eq!(clamp(f32::INFINITY), 1.0);
232        assert_eq!(clamp(f32::NEG_INFINITY), 0.0);
233    }
234
235    #[test]
236    fn clamp_maps_nan_to_zero() {
237        assert_eq!(clamp(f32::NAN), 0.0);
238        assert_eq!(progress(f32::NAN).value(), 0.0);
239    }
240
241    #[test]
242    fn builder_clamps_its_value() {
243        assert_eq!(progress(-1.0).value(), 0.0);
244        assert_eq!(progress(2.0).value(), 1.0);
245    }
246
247    #[test]
248    fn percentage_rounds_and_clamps() {
249        assert_eq!(percentage(0.0), 0);
250        assert_eq!(percentage(0.424), 42);
251        assert_eq!(percentage(0.425), 43);
252        assert_eq!(percentage(1.0), 100);
253        assert_eq!(percentage(7.0), 100);
254        assert_eq!(percentage(-7.0), 0);
255        assert_eq!(percentage(f32::NAN), 0);
256    }
257
258    #[test]
259    fn sizes_grow_monotonically() {
260        let girths = Size::ALL.map(Size::girth);
261        assert!(girths.windows(2).all(|w| w[0] < w[1]));
262    }
263
264    #[test]
265    fn track_is_a_faint_version_of_the_bar() {
266        for theme in [light(), dark()] {
267            let tokens = Tokens::of(&theme);
268            for variant in Variant::ALL {
269                let colours = colours(&tokens, variant);
270                assert_ne!(colours.track, colours.bar, "{variant:?}");
271                assert_ne!(colours.track, tokens.background, "{variant:?}");
272            }
273        }
274    }
275
276    #[test]
277    fn variants_use_their_tokens() {
278        for theme in [light(), dark()] {
279            let tokens = Tokens::of(&theme);
280            assert_eq!(colours(&tokens, Variant::Default).bar, tokens.primary);
281            assert_eq!(colours(&tokens, Variant::Success).bar, tokens.success);
282            assert_eq!(colours(&tokens, Variant::Warning).bar, tokens.warning);
283            assert_eq!(
284                colours(&tokens, Variant::Destructive).bar,
285                tokens.destructive
286            );
287            assert_eq!(
288                style(&tokens, Variant::Default).border.radius,
289                radius::FULL.into()
290            );
291        }
292    }
293}