Skip to main content

gpui_material_components/
progress.rs

1mod motion;
2mod paint;
3
4use gpui::{
5    App, Bounds, ContentMask, ElementId, Hsla, IntoElement, ParentElement, Pixels, RenderOnce,
6    SharedString, StatefulInteractiveElement, Styled, Window, canvas, px,
7};
8use gpui_material_foundation::{animate, color, current_material_theme, is_bounds_visible};
9use gpui_material_theme::{ColorRole, Direction, MotionKind, MotionSpec, MotionSpeed};
10
11use crate::SemanticTone;
12use motion::{ProgressMotion, circular_indeterminate, linear_indeterminate};
13use paint::{ProgressPaint, Stroke, paint_stop, stop_bounds};
14
15const STROKE_WIDTH: f32 = 4.;
16const TRACK_GAP: f32 = 4.;
17const STOP_SIZE: f32 = 4.;
18const LINEAR_AMPLITUDE: f32 = 3.;
19const CIRCULAR_AMPLITUDE: f32 = 1.6;
20const CIRCULAR_WAVELENGTH: f32 = 15.;
21const MIN_WAVELENGTH: f32 = 1.;
22const MAX_WAVES: f32 = 128.;
23
24/// Straight or Expressive wavy active progress indicator.
25#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
26pub enum ProgressShape {
27    /// Standard flat bar or circular arc.
28    #[default]
29    Straight,
30    /// Expressive animated sine-wave active stroke.
31    Wavy,
32}
33
34/// Shape at the ends of a progress stroke.
35#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
36pub enum ProgressCap {
37    /// Semicircular stroke end caps (default).
38    #[default]
39    Round,
40    /// Flat stroke ends flush with the segment endpoints.
41    Butt,
42    /// Square stroke ends extending half the stroke width past the endpoints.
43    Square,
44}
45
46/// Per-stroke appearance. The default width is 4 dp and the color comes from
47/// the window palette's active or track role.
48#[derive(Clone, Copy, Debug, Default, PartialEq)]
49pub struct ProgressStroke {
50    /// Stroke thickness in logical pixels. Defaults to `4 px`.
51    pub width: Option<Pixels>,
52    /// Explicit stroke color overriding the theme or semantic tone role.
53    pub color: Option<Hsla>,
54    /// End-cap geometry for this stroke.
55    pub cap: ProgressCap,
56}
57
58/// Geometry and appearance passed to a linear determinate stop painter.
59#[derive(Clone, Copy, Debug, PartialEq)]
60pub struct ProgressStop {
61    /// Clipped bounding box of the trailing stop indicator.
62    pub bounds: Bounds<Pixels>,
63    /// Resolved active indicator color.
64    pub color: Hsla,
65    /// Active stroke cap style.
66    pub cap: ProgressCap,
67    /// Active layout direction (`Ltr` or `Rtl`).
68    pub direction: Direction,
69}
70
71type StopPainter = dyn Fn(ProgressStop, &mut Window, &mut App);
72
73fn progress_tone_roles(tone: SemanticTone) -> (ColorRole, ColorRole) {
74    tone.roles().map_or(
75        (ColorRole::Primary, ColorRole::SecondaryContainer),
76        |(role, _, container, _)| (role, container),
77    )
78}
79
80struct Progress {
81    id: ElementId,
82    name: SharedString,
83    value: Option<f32>,
84    shape: ProgressShape,
85    tone: SemanticTone,
86    active: ProgressStroke,
87    track: ProgressStroke,
88    gap: f32,
89    stop_size: f32,
90    stop_painter: Option<Box<StopPainter>>,
91    amplitude: Option<Box<dyn Fn(f32) -> f32>>,
92    wavelength: Option<f32>,
93    wave_speed: Option<f32>,
94}
95
96impl Progress {
97    fn new(id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
98        Self {
99            id: id.into(),
100            name: name.into(),
101            value: None,
102            shape: ProgressShape::default(),
103            tone: SemanticTone::Default,
104            active: ProgressStroke::default(),
105            track: ProgressStroke::default(),
106            gap: TRACK_GAP,
107            stop_size: STOP_SIZE,
108            stop_painter: None,
109            amplitude: None,
110            wavelength: None,
111            wave_speed: None,
112        }
113    }
114
115    fn render(self, circular: bool, window: &mut Window, cx: &mut App) -> impl IntoElement {
116        let theme = current_material_theme(window, cx);
117        let (active_role, track_role) = progress_tone_roles(self.tone);
118        let active = Stroke::resolve(self.active, color(theme.colors.color(active_role)));
119        let track = Stroke::resolve(self.track, color(theme.colors.color(track_role)));
120        let reduced = cx.reduce_motion();
121        let window_active = window.is_window_active();
122        let direction = theme.layout.direction;
123        let value = self
124            .value
125            .filter(|v| v.is_finite())
126            .map(|v| v.clamp(0., 1.));
127        let measured = value.is_some();
128        let motion = window.use_keyed_state((self.id.clone(), "progress-motion"), cx, |_, _| {
129            ProgressMotion::new(value.unwrap_or(0.4))
130        });
131        let (target, visible) = motion.update(cx, |state, _| {
132            if let Some(value) = value {
133                state.last_measured = value;
134            }
135            (state.last_measured, state.visible)
136        });
137        let instant = reduced || !window_active || !window.is_visible() || !visible;
138        let effects = theme
139            .motion
140            .spec(MotionKind::Effects, MotionSpeed::Default, instant);
141        let spatial = theme
142            .motion
143            .spec(MotionKind::Spatial, MotionSpeed::Default, instant);
144        let mode = animate(
145            (self.id.clone(), "indeterminate-mix"),
146            f32::from(!measured),
147            effects,
148            window,
149            cx,
150        )
151        .clamp(0., 1.);
152        let measured_value = animate(
153            (self.id.clone(), "determinate-value"),
154            target,
155            spatial,
156            window,
157            cx,
158        )
159        .clamp(0., 1.);
160        let wavy = self.shape == ProgressShape::Wavy;
161        let amplitude = if wavy {
162            let endpoint = mode == 0. && (measured_value == 0. || measured_value == 1.);
163            let default_target = wave_amplitude(measured_value) * (1. - mode) + mode;
164            let target = self.amplitude.as_ref().map_or(default_target, |amplitude| {
165                normalized_amplitude(amplitude(if measured { measured_value } else { 0. }))
166            });
167            animate(
168                (self.id.clone(), "wave-amplitude"),
169                if endpoint { 0. } else { target },
170                if endpoint {
171                    MotionSpec::Instant
172                } else {
173                    effects
174                },
175                window,
176                cx,
177            )
178            .clamp(0., 1.)
179        } else {
180            0.
181        };
182        let wavelength = self
183            .wavelength
184            .unwrap_or(if circular {
185                CIRCULAR_WAVELENGTH
186            } else {
187                40. - 20. * mode
188            })
189            .max(MIN_WAVELENGTH);
190        let hz = self
191            .wave_speed
192            .map_or(1., |speed| f64::from(speed) / f64::from(wavelength));
193        let motion_enabled = window_active && window.is_visible() && !reduced && active.width > 0.;
194        let animate_loop = motion_enabled && !measured;
195        let animate_wave =
196            motion_enabled && hz > 0. && amplitude > 0. && (mode > 0. || measured_value > 0.);
197        let now = cx.background_executor().now();
198        let (loop_time, phase) = motion.update(cx, |state, _| {
199            let visible = state.visible;
200            state.sample(
201                now,
202                animate_loop && visible,
203                if animate_wave && visible { hz } else { 0. },
204                reduced,
205                mode == 1.,
206            )
207        });
208        let motionless = reduced || !window_active && loop_time == 0.;
209        let (arc_start, arc_length) = if circular && mode > 0. && !motionless {
210            circular_indeterminate(loop_time)
211        } else {
212            (0., 0.25)
213        };
214        let arc_origin = motion.update(cx, |state, _| {
215            if mode == 0. || mode == 1. || motionless {
216                state.arc_origin = arc_start.round();
217            }
218            state.arc_origin
219        });
220        let arc = (
221            (arc_start - arc_origin) * mode,
222            measured_value + (arc_length - measured_value) * mode,
223        );
224        let [first, second] = if circular || mode == 0. || motionless {
225            [(0.25, 0.65), (0., 0.)]
226        } else {
227            linear_indeterminate(loop_time)
228        };
229        let mut lines = [
230            (
231                first.0 * mode,
232                measured_value + (first.1 - measured_value) * mode,
233            ),
234            (second.0, second.0 + (second.1 - second.0) * mode),
235        ];
236        lines.sort_by(|left, right| left.0.total_cmp(&right.0));
237
238        let wave_space = if wavy { 2. * LINEAR_AMPLITUDE } else { 0. };
239        let side = if circular {
240            if wavy { 48. } else { 40. }
241        } else {
242            STROKE_WIDTH
243                .max(active.width)
244                .max(track.width)
245                .max(self.stop_size)
246                + wave_space
247        };
248        let picture = canvas(
249            |_, _, _| (),
250            move |bounds, _, window, cx| {
251                let width = f32::from(bounds.size.width);
252                let height = f32::from(bounds.size.height);
253                let visible = width.is_finite()
254                    && height.is_finite()
255                    && width > 0.
256                    && height > 0.
257                    && is_bounds_visible(bounds, window);
258                let now = cx.background_executor().now();
259                motion.update(cx, |state, _| state.set_visible(visible, now));
260                if !visible {
261                    return;
262                }
263                window.with_content_mask(Some(ContentMask { bounds }), |window| {
264                    let paint = ProgressPaint {
265                        active,
266                        track,
267                        gap: self.gap,
268                        wavelength,
269                        amplitude,
270                        phase,
271                    };
272                    if circular {
273                        paint.circular(bounds, arc, wavy, window);
274                    } else {
275                        paint.linear(bounds, lines, direction, window);
276                        if measured && self.stop_size > 0. {
277                            let stop = ProgressStop {
278                                bounds: stop_bounds(bounds, self.stop_size, wavy, direction),
279                                color: active.color,
280                                cap: active.cap,
281                                direction,
282                            };
283                            paint_stop(stop, self.stop_painter.as_deref(), window, cx);
284                        }
285                    }
286                });
287                if animate_loop || animate_wave {
288                    window.request_animation_frame();
289                }
290            },
291        )
292        .size_full();
293        let mut element = gpui_base::Progress::new(self.id)
294            .value(value.unwrap_or_default() * 100.)
295            .indeterminate(!measured)
296            .accessibility_label(self.name)
297            .h(px(side))
298            .child(picture);
299        if !measured {
300            element = element.a11y_synthetic_children(|node| {
301                node.parent_node().set_live(gpui::accesskit::Live::Polite);
302                node.parent_node().set_live_atomic();
303            });
304        }
305        if circular {
306            element = element.w(px(side)).flex_none();
307        } else {
308            element = element.w_full();
309        }
310        element
311    }
312}
313
314fn nonnegative_length(value: Pixels) -> Option<f32> {
315    let length = f32::from(value);
316    (length.is_finite() && length >= 0.).then_some(length)
317}
318
319fn normalized_amplitude(amplitude: f32) -> f32 {
320    if amplitude.is_nan() {
321        0.
322    } else {
323        amplitude.clamp(0., 1.)
324    }
325}
326
327fn wave_amplitude(progress: f32) -> f32 {
328    // WavyProgressIndicatorDefaults.indicatorAmplitude suppresses waves at the
329    // beginning and end; only the change between these targets is animated.
330    f32::from(progress > 0.1 && progress < 0.95)
331}
332
333/// Horizontal progress. Supply a fraction from 0 to 1, or omit it for indeterminate progress.
334#[derive(IntoElement)]
335pub struct LinearProgress(Progress);
336
337/// Circular progress. Supply a fraction from 0 to 1, or omit it for indeterminate progress.
338#[derive(IntoElement)]
339pub struct CircularProgress(Progress);
340
341impl LinearProgress {
342    /// Sets the determinate stop marker's size. Zero hides the marker.
343    pub fn stop_size(mut self, size: Pixels) -> Self {
344        self.0.stop_size = nonnegative_length(size).unwrap_or(STOP_SIZE);
345        self
346    }
347
348    /// Replaces the determinate stop marker's paint within its clipped bounds.
349    pub fn draw_stop_indicator(
350        mut self,
351        draw: impl Fn(ProgressStop, &mut Window, &mut App) + 'static,
352    ) -> Self {
353        self.0.stop_painter = Some(Box::new(draw));
354        self
355    }
356}
357
358macro_rules! progress_api {
359    ($name:ident, $circular:literal) => {
360        impl $name {
361            /// Creates an indeterminate progress indicator with the given element ID and accessible name.
362            pub fn new(id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
363                Self(Progress::new(id, name))
364            }
365
366            /// Sets determinate progress as a fraction in `0.0..=1.0` (clamped during render).
367            pub fn value(mut self, value: f32) -> Self {
368                self.0.value = Some(value);
369                self
370            }
371
372            /// Clears the measured value and shows indeterminate progress.
373            pub fn indeterminate(mut self) -> Self {
374                self.0.value = None;
375                self
376            }
377
378            /// Selects straight or Expressive wavy active stroke geometry.
379            pub fn shape(mut self, shape: ProgressShape) -> Self {
380                self.0.shape = shape;
381                self
382            }
383
384            /// Applies a Material 3 semantic tone shortcut to the active and track strokes.
385            /// Explicit `.active_stroke` and `.track_stroke` colors still take precedence.
386            pub fn tone(mut self, tone: SemanticTone) -> Self {
387                self.0.tone = tone;
388                self
389            }
390
391            /// Overrides the active indicator stroke width, color, and cap.
392            pub fn active_stroke(mut self, stroke: ProgressStroke) -> Self {
393                self.0.active = stroke;
394                self
395            }
396
397            /// Overrides the background track stroke width, color, and cap.
398            pub fn track_stroke(mut self, stroke: ProgressStroke) -> Self {
399                self.0.track = stroke;
400                self
401            }
402
403            /// Sets the painted gap between the active stroke and the track.
404            pub fn gap(mut self, gap: Pixels) -> Self {
405                self.0.gap = nonnegative_length(gap).unwrap_or(TRACK_GAP);
406                self
407            }
408
409            /// Sets a fraction of the available height or radius for the wave.
410            pub fn wave_amplitude(self, fraction: f32) -> Self {
411                self.wave_amplitude_by(move |_| fraction)
412            }
413
414            /// Computes the wave amplitude from displayed progress. In
415            /// indeterminate mode the function receives zero.
416            pub fn wave_amplitude_by(mut self, amplitude: impl Fn(f32) -> f32 + 'static) -> Self {
417                self.0.amplitude = Some(Box::new(amplitude));
418                self
419            }
420
421            /// Sets crest spacing in logical pixels. Clamped to a minimum of `1 px` to avoid numerical overflow.
422            pub fn wavelength(mut self, length: Pixels) -> Self {
423                self.0.wavelength = nonnegative_length(length)
424                    .filter(|length| *length > 0.)
425                    .map(|length| length.max(MIN_WAVELENGTH));
426                self
427            }
428
429            /// Sets travel speed in logical pixels per second. Zero holds the phase.
430            pub fn wave_speed(mut self, length_per_second: Pixels) -> Self {
431                self.0.wave_speed = nonnegative_length(length_per_second);
432                self
433            }
434        }
435
436        impl RenderOnce for $name {
437            fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
438                self.0.render($circular, window, cx)
439            }
440        }
441    };
442}
443
444progress_api!(LinearProgress, false);
445progress_api!(CircularProgress, true);
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450
451    #[test]
452    fn progress_tone_roles_map_semantic_tones() {
453        use ColorRole::*;
454        assert_eq!(
455            progress_tone_roles(SemanticTone::Default),
456            (Primary, SecondaryContainer)
457        );
458        assert_eq!(
459            progress_tone_roles(SemanticTone::Danger),
460            (Error, ErrorContainer)
461        );
462        assert_eq!(
463            progress_tone_roles(SemanticTone::Success),
464            (Success, SuccessContainer)
465        );
466        assert_eq!(
467            progress_tone_roles(SemanticTone::Warning),
468            (Warning, WarningContainer)
469        );
470        assert_eq!(
471            progress_tone_roles(SemanticTone::Info),
472            (Info, InfoContainer)
473        );
474    }
475
476    #[test]
477    fn wavelength_clamps_minimum_and_rejects_non_finite_values() {
478        let clamped = LinearProgress::new("p1", "Loading").wavelength(px(f32::MIN_POSITIVE));
479        assert_eq!(clamped.0.wavelength, Some(MIN_WAVELENGTH));
480
481        let sub_pixel = CircularProgress::new("p2", "Loading").wavelength(px(0.25));
482        assert_eq!(sub_pixel.0.wavelength, Some(MIN_WAVELENGTH));
483
484        let valid = LinearProgress::new("p3", "Loading").wavelength(px(12.));
485        assert_eq!(valid.0.wavelength, Some(12.));
486
487        for invalid in [0., -5., f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
488            let progress = LinearProgress::new("p4", "Loading").wavelength(px(invalid));
489            assert_eq!(progress.0.wavelength, None);
490        }
491    }
492}