Skip to main content

gpui_component/progress/
progress_circle.rs

1use crate::{ActiveTheme, Sizable, Size};
2use gpui::Bounds;
3use gpui::ColorExt as _;
4use gpui::prelude::FluentBuilder as _;
5use gpui::{
6    Animation, AnimationExt as _, AnyElement, App, ElementId, Hsla, IntoElement, ParentElement,
7    Pixels, RenderOnce, SharedString, StyleRefinement, Styled, Window, canvas, ease_in_out, px,
8    relative,
9};
10use gpui_base::{Progress as BaseProgress, Transition, transition};
11use std::f32::consts::TAU;
12use web_time::Duration;
13
14use crate::plot::shape::{Arc, ArcData};
15
16/// A circular progress indicator element.
17#[derive(IntoElement)]
18pub struct ProgressCircle {
19    id: ElementId,
20    style: StyleRefinement,
21    color: Option<Hsla>,
22    value: f32,
23    accessibility_label: Option<SharedString>,
24    size: Size,
25    children: Vec<AnyElement>,
26    loading: bool,
27}
28
29impl ProgressCircle {
30    /// Create a new circular progress indicator.
31    pub fn new(id: impl Into<ElementId>) -> Self {
32        Self {
33            id: id.into(),
34            value: Default::default(),
35            color: None,
36            accessibility_label: None,
37            style: StyleRefinement::default(),
38            size: Size::default(),
39            children: Vec::new(),
40            loading: false,
41        }
42    }
43
44    /// Enable indeterminate loading animation.
45    ///
46    /// When `loading` is `true`, the `value` is ignored and an infinite
47    /// rotating arc animation is shown instead.
48    pub fn loading(mut self, loading: bool) -> Self {
49        self.loading = loading;
50        self
51    }
52
53    /// Set the color of the progress circle.
54    pub fn color(mut self, color: impl Into<Hsla>) -> Self {
55        self.color = Some(color.into());
56        self
57    }
58
59    /// Set the percentage value of the progress circle.
60    ///
61    /// The value should be between 0.0 and 100.0.
62    pub fn value(mut self, value: f32) -> Self {
63        self.value = value.clamp(0., 100.);
64        self
65    }
66
67    /// Set the accessible name exposed by the progress indicator.
68    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
69        self.accessibility_label = Some(label.into());
70        self
71    }
72
73    /// Render the arc canvas. `start_value` and `end_value` are in 0.0–100.0 percentage.
74    /// The progress arc is skipped when `end_value <= 0`.
75    fn render_circle(start_value: f32, end_value: f32, color: Hsla) -> impl IntoElement {
76        struct PrepaintState {
77            start_value: f32,
78            end_value: f32,
79            actual_inner_radius: f32,
80            actual_outer_radius: f32,
81            bounds: Bounds<Pixels>,
82        }
83
84        canvas(
85            move |bounds: Bounds<Pixels>, _window: &mut Window, _cx: &mut App| {
86                let stroke_width = (bounds.size.width * 0.15).min(px(5.));
87                let actual_size = bounds.size.width.min(bounds.size.height);
88                let actual_radius = (actual_size.as_f32() - stroke_width.as_f32()) / 2.;
89                PrepaintState {
90                    start_value,
91                    end_value,
92                    actual_inner_radius: actual_radius - stroke_width.as_f32() / 2.,
93                    actual_outer_radius: actual_radius + stroke_width.as_f32() / 2.,
94                    bounds,
95                }
96            },
97            move |_bounds, prepaint, window: &mut Window, _cx: &mut App| {
98                let arc = Arc::new()
99                    .inner_radius(prepaint.actual_inner_radius)
100                    .outer_radius(prepaint.actual_outer_radius);
101
102                arc.paint(
103                    &ArcData::new(&(), 0, 100., 0., TAU),
104                    color.opacity(0.2),
105                    &prepaint.bounds,
106                    window,
107                );
108
109                if prepaint.end_value > 0. {
110                    let start_angle = (prepaint.start_value / 100.) * TAU;
111                    let end_angle = (prepaint.end_value / 100.) * TAU;
112                    arc.paint(
113                        &ArcData::new(&(), 1, prepaint.end_value, start_angle, end_angle),
114                        color,
115                        &prepaint.bounds,
116                        window,
117                    );
118                }
119            },
120        )
121        .absolute()
122        .size_full()
123    }
124}
125
126impl Styled for ProgressCircle {
127    fn style(&mut self) -> &mut StyleRefinement {
128        &mut self.style
129    }
130}
131
132impl Sizable for ProgressCircle {
133    fn with_size(mut self, size: impl Into<Size>) -> Self {
134        self.size = size.into();
135        self
136    }
137}
138
139impl ParentElement for ProgressCircle {
140    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
141        self.children.extend(elements);
142    }
143}
144
145impl RenderOnce for ProgressCircle {
146    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
147        let value = self.value;
148        let loading = self.loading;
149        let accessibility_label = self.accessibility_label;
150        let animated_value = transition(
151            (self.id.clone(), "value"),
152            value,
153            Transition::new(cx.theme().motion_tokens().duration_normal)
154                .easing(cx.theme().motion_tokens().easing_move.clone()),
155            window,
156            cx,
157        );
158
159        let color = self.color.unwrap_or(cx.theme().progress_bar);
160
161        BaseProgress::new(self.id.clone())
162            .value(value)
163            .indeterminate(loading)
164            .when_some(accessibility_label, |this, label| {
165                this.accessibility_label(label)
166            })
167            .flex()
168            .items_center()
169            .justify_center()
170            .line_height(relative(1.))
171            .map(|this| match self.size {
172                Size::XSmall => this.size_2(),
173                Size::Small => this.size_3(),
174                Size::Medium => this.size_4(),
175                Size::Large => this.size_5(),
176                Size::Size(s) => this.size(s * 0.75),
177            })
178            .refine_style(&self.style)
179            .children(self.children)
180            .map(|this| {
181                if loading {
182                    this.with_animation(
183                        "progress-circle-loading",
184                        Animation::new(Duration::from_secs(1)).repeat(),
185                        move |this, delta| {
186                            let end = ease_in_out(delta) * 100.;
187                            let start = ease_in_out(((delta - 0.5) / 0.5).clamp(0., 1.)) * 100.;
188                            this.child(Self::render_circle(start, end, color))
189                        },
190                    )
191                    .into_any_element()
192                } else {
193                    this.child(Self::render_circle(0., animated_value, color))
194                        .into_any_element()
195                }
196            })
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    #[test]
205    fn stores_an_explicit_accessibility_label() {
206        let plain = ProgressCircle::new("upload");
207        assert_eq!(plain.accessibility_label, None);
208
209        let named = ProgressCircle::new("upload").accessibility_label("Upload progress");
210        assert_eq!(
211            named.accessibility_label.as_deref(),
212            Some("Upload progress")
213        );
214    }
215}