Skip to main content

gpui_component/progress/
progress.rs

1use crate::{ActiveTheme, Sizable, Size, StyledExt};
2use gpui::{
3    Animation, AnimationExt as _, App, Background, ElementId, Hsla, IntoElement, IsZero as _,
4    ParentElement, RenderOnce, SharedString, StyleRefinement, Styled, Window, ease_in_out,
5    prelude::FluentBuilder, px, relative,
6};
7use gpui_base::{
8    LayoutDirection, LogicalStyledExt as _, Progress as BaseProgress, ProgressIndicator,
9    ProgressTrack, Transition, transition,
10};
11use instant::Duration;
12
13/// A linear horizontal progress bar element.
14#[derive(IntoElement)]
15pub struct Progress {
16    id: ElementId,
17    style: StyleRefinement,
18    color: Option<Hsla>,
19    value: f32,
20    accessibility_label: Option<SharedString>,
21    size: Size,
22    loading: bool,
23}
24
25impl Progress {
26    /// Create a new Progress bar.
27    pub fn new(id: impl Into<ElementId>) -> Self {
28        Self {
29            id: id.into(),
30            value: Default::default(),
31            color: None,
32            accessibility_label: None,
33            style: StyleRefinement::default(),
34            size: Size::default(),
35            loading: false,
36        }
37    }
38
39    /// Enable indeterminate loading animation.
40    ///
41    /// When `loading` is `true`, the `value` is ignored and an infinite
42    /// sliding animation is shown instead.
43    pub fn loading(mut self, loading: bool) -> Self {
44        self.loading = loading;
45        self
46    }
47
48    /// Set the color of the progress bar.
49    pub fn color(mut self, color: impl Into<Hsla>) -> Self {
50        self.color = Some(color.into());
51        self
52    }
53
54    /// Set the percentage value of the progress bar.
55    ///
56    /// The value should be between 0.0 and 100.0.
57    pub fn value(mut self, value: f32) -> Self {
58        self.value = value.clamp(0., 100.);
59        self
60    }
61
62    /// Set the accessible name exposed by the progress indicator.
63    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
64        self.accessibility_label = Some(label.into());
65        self
66    }
67}
68
69impl Styled for Progress {
70    fn style(&mut self) -> &mut StyleRefinement {
71        &mut self.style
72    }
73}
74
75impl Sizable for Progress {
76    fn with_size(mut self, size: impl Into<Size>) -> Self {
77        self.size = size.into();
78        self
79    }
80}
81
82impl RenderOnce for Progress {
83    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
84        let bg = self
85            .color
86            .map(Background::from)
87            .unwrap_or(cx.theme().tokens.progress_bar.into());
88        let value = self.value;
89        let loading = self.loading;
90        let accessibility_label = self.accessibility_label;
91        let reduce_motion = cx.reduce_motion();
92        let rtl = LayoutDirection::global(cx).is_rtl();
93
94        let radius = self.style.corner_radii.clone();
95        let mut inner_style = StyleRefinement::default();
96        inner_style.corner_radii = radius;
97
98        let (height, pill_radius) = match self.size {
99            Size::XSmall => (px(4.), px(2.)),
100            Size::Small => (px(6.), px(3.)),
101            Size::Medium => (px(8.), px(4.)),
102            Size::Large => (px(10.), px(5.)),
103            Size::Size(s) => (s, s / 2.),
104        };
105        // The bar reads as a pill of half its own height, and squares off with
106        // the rest of the UI when the theme has no radius.
107        let radius = if cx.theme().radius.is_zero() {
108            px(0.)
109        } else {
110            pill_radius
111        };
112
113        let animated_value = transition(
114            (self.id.clone(), "indicator"),
115            value,
116            Transition::new(cx.theme().motion_tokens().duration_normal)
117                .easing(cx.theme().motion_tokens().easing_move.clone()),
118            window,
119            cx,
120        );
121
122        BaseProgress::new(self.id)
123            .value(value)
124            .indeterminate(loading)
125            .when_some(accessibility_label, |this, label| {
126                this.accessibility_label(label)
127            })
128            .w_full()
129            .relative()
130            .h(height)
131            .rounded(radius)
132            .refine_style(&self.style)
133            .child(
134                ProgressTrack::new()
135                    .absolute()
136                    .size_full()
137                    .bg(bg.opacity(0.2))
138                    .rounded(radius)
139                    .refine_style(&inner_style),
140            )
141            .child(
142                ProgressIndicator::new()
143                    .absolute()
144                    .top_0()
145                    // Progress fills from the start edge: the right in RTL.
146                    .inset_s(px(0.), cx)
147                    .h_full()
148                    .bg(bg)
149                    .rounded(radius)
150                    .refine_style(&inner_style)
151                    .map(|this| {
152                        if loading && !reduce_motion {
153                            this.with_animation(
154                                "progress-loading",
155                                Animation::new(Duration::from_secs(1)).repeat(),
156                                move |this, delta| {
157                                    let start =
158                                        relative(ease_in_out(((delta - 0.5) / 0.5).clamp(0., 1.)));
159                                    let end = relative(ease_in_out(1.0 - delta));
160                                    if rtl {
161                                        this.when(delta > 0.5, |this| this.right(start)).left(end)
162                                    } else {
163                                        this.when(delta > 0.5, |this| this.left(start)).right(end)
164                                    }
165                                },
166                            )
167                            .into_any_element()
168                        } else if loading {
169                            this.left(relative(0.325))
170                                .right(relative(0.325))
171                                .into_any_element()
172                        } else {
173                            this.w(relative((animated_value / 100.).clamp(0., 1.)))
174                                .into_any_element()
175                        }
176                    }),
177            )
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    #[test]
186    fn stores_an_explicit_accessibility_label() {
187        let plain = Progress::new("upload");
188        assert_eq!(plain.accessibility_label, None);
189
190        let named = Progress::new("upload").accessibility_label("Upload progress");
191        assert_eq!(
192            named.accessibility_label.as_deref(),
193            Some("Upload progress")
194        );
195    }
196}