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