Skip to main content

fc_ui/capabilities/primitives/
progress.rs

1use crate::capabilities::foundation::theme::use_theme;
2use gpui::{prelude::FluentBuilder as _, *};
3
4/// Progress bar variants
5#[derive(Copy, Clone, Debug, PartialEq, Eq)]
6pub enum ProgressVariant {
7    /// Default blue progress bar
8    Default,
9    /// Success/complete state (green)
10    Success,
11    /// Warning state (yellow/orange)
12    Warning,
13    /// Error/failure state (red)
14    Destructive,
15}
16
17/// Progress bar sizes
18#[derive(Copy, Clone, Debug, PartialEq, Eq)]
19pub enum ProgressSize {
20    /// Thin progress bar (h-1)
21    Sm,
22    /// Default height (h-2)
23    Md,
24    /// Larger height (h-3)
25    Lg,
26}
27
28/// Spinner types for circular progress indicators
29#[derive(Copy, Clone, Debug, PartialEq, Eq)]
30pub enum SpinnerType {
31    /// Single orbiting dot on a track
32    Dot,
33    /// Arc segment (longer than dot) on a track
34    Arc,
35    /// Arc segment rotating without visible track
36    ArcNoTrack,
37    /// Growing circle that fills from dot to complete circle (for determinate progress)
38    GrowingCircle,
39}
40
41/// Progress bar component with determinate and indeterminate modes
42#[derive(IntoElement)]
43pub struct ProgressBar {
44    /// Progress value (0.0 to 1.0 for determinate, None for indeterminate)
45    value: Option<f32>,
46    variant: ProgressVariant,
47    size: ProgressSize,
48    /// Optional label to show percentage or custom text
49    label: Option<SharedString>,
50    /// Show percentage text overlay
51    show_percentage: bool,
52    style: StyleRefinement,
53}
54
55impl ProgressBar {
56    /// Create a new progress bar with a value (0.0 to 1.0)
57    pub fn new(value: f32) -> Self {
58        Self {
59            value: Some(value.clamp(0.0, 1.0)),
60            variant: ProgressVariant::Default,
61            size: ProgressSize::Md,
62            label: None,
63            show_percentage: false,
64            style: StyleRefinement::default(),
65        }
66    }
67
68    /// Create an indeterminate progress bar (loading animation)
69    pub fn indeterminate() -> Self {
70        Self {
71            value: None,
72            variant: ProgressVariant::Default,
73            size: ProgressSize::Md,
74            label: None,
75            show_percentage: false,
76            style: StyleRefinement::default(),
77        }
78    }
79
80    /// Set the progress variant
81    pub fn variant(mut self, variant: ProgressVariant) -> Self {
82        self.variant = variant;
83        self
84    }
85
86    /// Set the progress size
87    pub fn size(mut self, size: ProgressSize) -> Self {
88        self.size = size;
89        self
90    }
91
92    /// Set a custom label
93    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
94        self.label = Some(label.into());
95        self
96    }
97
98    /// Show percentage text (only for determinate progress)
99    pub fn show_percentage(mut self, show: bool) -> Self {
100        self.show_percentage = show;
101        self
102    }
103}
104
105impl Styled for ProgressBar {
106    fn style(&mut self) -> &mut StyleRefinement {
107        &mut self.style
108    }
109}
110
111impl RenderOnce for ProgressBar {
112    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
113        let theme = use_theme(cx);
114        let user_style = self.style;
115
116        let height = match self.size {
117            ProgressSize::Sm => px(4.0),
118            ProgressSize::Md => px(8.0),
119            ProgressSize::Lg => px(12.0),
120        };
121
122        let bar_color = match self.variant {
123            ProgressVariant::Default => theme.tokens.primary,
124            ProgressVariant::Success => rgb(0x22c55e).into(), // green-500
125            ProgressVariant::Warning => rgb(0xf59e0b).into(), // amber-500
126            ProgressVariant::Destructive => theme.tokens.destructive,
127        };
128
129        let progress_width = if let Some(value) = self.value {
130            relative(value)
131        } else {
132            relative(0.3) // Indeterminate shows 30% width animated
133        };
134
135        let percentage_text = self.value.map(|v| format!("{}%", (v * 100.0) as u32));
136
137        div()
138            .flex()
139            .flex_col()
140            .gap(px(8.0))
141            .w_full()
142            .when(
143                self.label.is_some() || (self.show_percentage && percentage_text.is_some()),
144                |this| {
145                    this.child(
146                        div()
147                            .flex()
148                            .justify_between()
149                            .items_center()
150                            .when_some(self.label, |this, label| {
151                                this.child(
152                                    div()
153                                        .text_sm()
154                                        .font_weight(FontWeight::MEDIUM)
155                                        .text_color(theme.tokens.foreground)
156                                        .child(label),
157                                )
158                            })
159                            .when(self.show_percentage && percentage_text.is_some(), |this| {
160                                this.child(
161                                    div()
162                                        .text_sm()
163                                        .text_color(theme.tokens.muted_foreground)
164                                        .child(percentage_text.unwrap_or_default()),
165                                )
166                            }),
167                    )
168                },
169            )
170            .child(
171                div()
172                    .relative()
173                    .w_full()
174                    .h(height)
175                    .rounded(theme.tokens.radius_lg)
176                    .bg(theme.tokens.muted)
177                    .overflow_hidden()
178                    .child(
179                        div()
180                            .absolute()
181                            .top_0()
182                            .left_0()
183                            .h_full()
184                            .w(progress_width)
185                            .bg(bar_color)
186                            .rounded(theme.tokens.radius_lg)
187                            .map(|this| {
188                                if self.value.is_none() {
189                                    this.with_animation(
190                                        "indeterminate-progress",
191                                        Animation::new(std::time::Duration::from_secs(2))
192                                            .repeat()
193                                            .with_easing(crate::capabilities::motion::animations::easings::linear),
194                                        |div, delta| {
195                                            let offset = (delta - 0.5) * 2.0;
196                                            div.left(relative(offset))
197                                        },
198                                    )
199                                    .into_any_element()
200                                } else {
201                                    this.into_any_element()
202                                }
203                            }),
204                    ),
205            )
206            .map(|this| {
207                let mut div = this;
208                div.style().refine(&user_style);
209                div
210            })
211    }
212}
213
214/// Circular progress/spinner component
215#[derive(IntoElement)]
216pub struct CircularProgress {
217    /// Progress value (0.0 to 1.0 for determinate, None for indeterminate)
218    value: Option<f32>,
219    size: Pixels,
220    stroke_width: Pixels,
221    variant: ProgressVariant,
222    spinner_type: SpinnerType,
223    style: StyleRefinement,
224}
225
226impl CircularProgress {
227    /// Create a new circular progress with a value
228    pub fn new(value: f32) -> Self {
229        Self {
230            value: Some(value.clamp(0.0, 1.0)),
231            size: px(40.0),
232            stroke_width: px(4.0),
233            variant: ProgressVariant::Default,
234            spinner_type: SpinnerType::Dot,
235            style: StyleRefinement::default(),
236        }
237    }
238
239    /// Create an indeterminate circular progress (spinner)
240    pub fn indeterminate() -> Self {
241        Self {
242            value: None,
243            size: px(40.0),
244            stroke_width: px(4.0),
245            variant: ProgressVariant::Default,
246            spinner_type: SpinnerType::Dot,
247            style: StyleRefinement::default(),
248        }
249    }
250
251    /// Set the size
252    pub fn size(mut self, size: Pixels) -> Self {
253        self.size = size;
254        self.stroke_width = size * 0.1; // Stroke is 10% of size
255        self
256    }
257
258    /// Set the variant
259    pub fn variant(mut self, variant: ProgressVariant) -> Self {
260        self.variant = variant;
261        self
262    }
263
264    /// Set the spinner type
265    pub fn spinner_type(mut self, spinner_type: SpinnerType) -> Self {
266        self.spinner_type = spinner_type;
267        self
268    }
269}
270
271impl Styled for CircularProgress {
272    fn style(&mut self) -> &mut StyleRefinement {
273        &mut self.style
274    }
275}
276
277impl RenderOnce for CircularProgress {
278    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
279        let theme = use_theme(cx);
280        let user_style = self.style;
281
282        let stroke_color = match self.variant {
283            ProgressVariant::Default => theme.tokens.primary,
284            ProgressVariant::Success => rgb(0x22c55e).into(),
285            ProgressVariant::Warning => rgb(0xf59e0b).into(),
286            ProgressVariant::Destructive => theme.tokens.destructive,
287        };
288
289        div()
290            .flex()
291            .items_center()
292            .justify_center()
293            .size(self.size)
294            .child(
295                div()
296                    .size(self.size)
297                    .rounded(px(9999.0))
298                    .relative()
299                    .map(|container| {
300                        let track_color = theme.tokens.muted;
301                        let stroke_w = self.stroke_width;
302                        let container = container.child(
303                            div()
304                                .absolute()
305                                .inset_0()
306                                .border(stroke_w)
307                                .border_color(track_color)
308                                .rounded(px(9999.0)),
309                        );
310
311                        match (self.value, self.spinner_type) {
312                            (Some(value), SpinnerType::GrowingCircle) => {
313                                let size_px = self.size;
314                                let center = size_px * 0.5;
315                                let path_radius = (size_px - stroke_w) * 0.5;
316                                let num_segments = 32; // More segments for smoother circle
317
318                                container
319                                    .children((0..num_segments).map(move |i| {
320                                        let segment_angle = (i as f32 / num_segments as f32)
321                                            * std::f32::consts::TAU;
322                                        let progress_threshold = i as f32 / num_segments as f32;
323
324                                        div()
325                                            .absolute()
326                                            .size(stroke_w * 1.2)
327                                            .rounded(px(9999.0))
328                                            .bg(stroke_color)
329                                            .left(
330                                                center + path_radius * segment_angle.cos()
331                                                    - stroke_w * 0.6,
332                                            )
333                                            .top(
334                                                center + path_radius * segment_angle.sin()
335                                                    - stroke_w * 0.6,
336                                            )
337                                            .opacity(if value >= progress_threshold {
338                                                1.0
339                                            } else {
340                                                0.0
341                                            })
342                                    }))
343                                    .into_any_element()
344                            }
345                            (Some(value), _) => container
346                                .child(
347                                    div()
348                                        .absolute()
349                                        .inset_0()
350                                        .border(stroke_w)
351                                        .border_color(stroke_color)
352                                        .rounded(px(9999.0))
353                                        .opacity(value * 0.7 + 0.3),
354                                )
355                                .into_any_element(),
356                            (None, SpinnerType::Dot) => {
357                                let size_px = self.size;
358                                let dot_diameter = stroke_w * 1.5;
359                                let dot_radius = dot_diameter * 0.5;
360                                let center = size_px * 0.5;
361                                let path_radius = (size_px - stroke_w) * 0.5;
362
363                                container
364                                    .child(
365                                        div()
366                                            .absolute()
367                                            .size(dot_diameter)
368                                            .rounded(px(9999.0))
369                                            .bg(stroke_color)
370                                            .with_animation(
371                                                "spinner-orbit",
372                                                Animation::new(std::time::Duration::from_millis(
373                                                    800,
374                                                ))
375                                                .repeat()
376                                                .with_easing(crate::capabilities::motion::animations::easings::linear),
377                                                move |dot, delta| {
378                                                    let angle = delta * std::f32::consts::TAU;
379                                                    let x = center + path_radius * angle.cos()
380                                                        - dot_radius;
381                                                    let y = center + path_radius * angle.sin()
382                                                        - dot_radius;
383                                                    dot.left(x).top(y)
384                                                },
385                                            ),
386                                    )
387                                    .into_any_element()
388                            }
389                            (None, SpinnerType::Arc) => {
390                                let size_px = self.size;
391                                let center = size_px * 0.5;
392                                let path_radius = (size_px - stroke_w) * 0.5;
393                                let num_dots = 8; // Number of dots in the arc
394
395                                container
396                                    .children((0..num_dots).map(move |i| {
397                                        let dot_angle = (i as f32 / num_dots as f32)
398                                            * std::f32::consts::PI
399                                            * 0.75; // Arc of about 135 degrees
400                                        div()
401                                            .absolute()
402                                            .size(stroke_w * 1.2)
403                                            .rounded(px(9999.0))
404                                            .bg(stroke_color)
405                                            .left(
406                                                center + path_radius * dot_angle.cos()
407                                                    - stroke_w * 0.6,
408                                            )
409                                            .top(
410                                                center + path_radius * dot_angle.sin()
411                                                    - stroke_w * 0.6,
412                                            )
413                                            .with_animation(
414                                                ("spinner-arc", i as u32),
415                                                Animation::new(std::time::Duration::from_millis(
416                                                    1000,
417                                                ))
418                                                .repeat()
419                                                .with_easing(crate::capabilities::motion::animations::easings::linear),
420                                                move |dot, delta| {
421                                                    let visibility = ((delta
422                                                        + i as f32 / num_dots as f32)
423                                                        % 1.0)
424                                                        < 0.6;
425                                                    dot.opacity(if visibility { 1.0 } else { 0.0 })
426                                                },
427                                            )
428                                    }))
429                                    .into_any_element()
430                            }
431                            (None, SpinnerType::ArcNoTrack) => {
432                                let size_px = self.size;
433                                let center = size_px * 0.5;
434                                let path_radius = (size_px - stroke_w) * 0.5;
435                                let num_dots = 8;
436
437                                div()
438                                    .size(size_px)
439                                    .relative()
440                                    .children((0..num_dots).map(move |i| {
441                                        div()
442                                            .absolute()
443                                            .size(stroke_w * 1.2)
444                                            .rounded(px(9999.0))
445                                            .bg(stroke_color)
446                                            .with_animation(
447                                                ("spinner-arc-no-track", i as u32),
448                                                Animation::new(std::time::Duration::from_millis(
449                                                    1000,
450                                                ))
451                                                .repeat()
452                                                .with_easing(crate::capabilities::motion::animations::easings::linear),
453                                                move |dot, delta| {
454                                                    let angle = delta * std::f32::consts::TAU
455                                                        + (i as f32 / num_dots as f32)
456                                                            * std::f32::consts::PI
457                                                            * 0.75;
458                                                    let x = center + path_radius * angle.cos()
459                                                        - stroke_w * 0.6;
460                                                    let y = center + path_radius * angle.sin()
461                                                        - stroke_w * 0.6;
462                                                    dot.left(x).top(y)
463                                                },
464                                            )
465                                    }))
466                                    .into_any_element()
467                            }
468                            (None, SpinnerType::GrowingCircle) => {
469                                let size_px = self.size;
470                                let center = size_px * 0.5;
471                                let path_radius = (size_px - stroke_w) * 0.5;
472                                let num_segments = 32;
473
474                                container
475                                    .children((0..num_segments).map(move |i| {
476                                        div()
477                                            .absolute()
478                                            .size(stroke_w * 1.2)
479                                            .rounded(px(9999.0))
480                                            .bg(stroke_color)
481                                            .with_animation(
482                                                ("growing-circle", i as u32),
483                                                Animation::new(std::time::Duration::from_millis(
484                                                    2000,
485                                                ))
486                                                .repeat()
487                                                .with_easing(crate::capabilities::motion::animations::easings::linear),
488                                                move |dot, delta| {
489                                                    let segment_angle = (i as f32
490                                                        / num_segments as f32)
491                                                        * std::f32::consts::TAU;
492                                                    let x = center
493                                                        + path_radius * segment_angle.cos()
494                                                        - stroke_w * 0.6;
495                                                    let y = center
496                                                        + path_radius * segment_angle.sin()
497                                                        - stroke_w * 0.6;
498                                                    let segment_progress =
499                                                        i as f32 / num_segments as f32;
500                                                    let visibility =
501                                                        (delta - segment_progress + 1.0) % 1.0
502                                                            < 0.3;
503                                                    dot.left(x).top(y).opacity(if visibility {
504                                                        1.0
505                                                    } else {
506                                                        0.0
507                                                    })
508                                                },
509                                            )
510                                    }))
511                                    .into_any_element()
512                            }
513                        }
514                    }),
515            )
516            .map(|this| {
517                let mut div = this;
518                div.style().refine(&user_style);
519                div
520            })
521    }
522}