Skip to main content

gpui_material_components/
progress.rs

1use std::{f32::consts::TAU, time::Duration};
2
3use gpui::{
4    App, Bounds, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement, PathBuilder,
5    Pixels, Point, RenderOnce, SharedString, StatefulInteractiveElement, Styled, Window, canvas,
6    div, point, px,
7};
8use gpui_base::motion::Easing;
9use gpui_material_foundation::{animate, color, window_material_theme};
10use gpui_material_theme::{ColorRole, Direction, MotionKind, MotionSpeed, TokenValue, token};
11use polymorpher::{Morph, shapes};
12use web_time::Instant;
13
14/// Straight or Expressive wavy progress track.
15#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
16pub enum ProgressShape {
17    #[default]
18    Straight,
19    Wavy,
20}
21
22struct Progress {
23    id: ElementId,
24    name: SharedString,
25    value: Option<f32>,
26    shape: ProgressShape,
27}
28
29impl Progress {
30    fn new(id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
31        Self {
32            id: id.into(),
33            name: name.into(),
34            value: None,
35            shape: ProgressShape::default(),
36        }
37    }
38
39    fn paint(self, circular: bool, window: &mut Window, cx: &mut App) -> impl IntoElement {
40        let now = cx.background_executor().now();
41        let epoch = *window
42            .use_keyed_state(ElementId::from((self.id.clone(), "phase")), cx, |_, _| now)
43            .read(cx);
44        let reduced = cx.reduce_motion();
45        let theme = window_material_theme(window, cx);
46        let policy = theme
47            .motion
48            .spec(MotionKind::Spatial, MotionSpeed::Default, reduced);
49        let active = color(theme.colors.color(ColorRole::Primary));
50        let track = color(theme.colors.color(ColorRole::SecondaryContainer));
51        let direction = theme.layout.direction;
52        let wavy = self.shape == ProgressShape::Wavy;
53        let value = self
54            .value
55            .filter(|value| value.is_finite())
56            .map(|value| value.clamp(0., 1.));
57        let animated = value.is_none() && !reduced;
58        let moving_wave = wavy && !reduced;
59        let mode_spec = theme
60            .motion
61            .spec(MotionKind::Effects, MotionSpeed::Default, reduced);
62        let indeterminate = animate(
63            (self.id.clone(), "indeterminate-mix"),
64            f32::from(value.is_none()),
65            mode_spec,
66            window,
67            cx,
68        )
69        .clamp(0., 1.);
70        let last_value = window.use_keyed_state((self.id.clone(), "last-progress"), cx, |_, _| {
71            value.unwrap_or(0.4)
72        });
73        let determinate = match value {
74            Some(value) => {
75                if value != *last_value.read(cx) {
76                    last_value.update(cx, |last, _| *last = value);
77                }
78                value
79            }
80            None => *last_value.read(cx),
81        };
82        let determinate = animate(
83            (self.id.clone(), "determinate-value"),
84            determinate,
85            policy,
86            window,
87            cx,
88        )
89        .clamp(0., 1.);
90        let wave_phase = if moving_wave {
91            now.saturating_duration_since(epoch).as_secs_f32().fract()
92        } else {
93            0.
94        };
95        let amplitude = animate(
96            (self.id.clone(), "wave-amplitude"),
97            wave_amplitude(determinate) + (1. - wave_amplitude(determinate)) * indeterminate,
98            mode_spec,
99            window,
100            cx,
101        )
102        .clamp(0., 1.);
103        let elapsed = now.saturating_duration_since(epoch).as_secs_f32() * 1000.;
104        let circular_segment = if !circular || reduced {
105            (0., 0.25)
106        } else {
107            circular_indeterminate(elapsed)
108        };
109        let loop_origin = window.use_keyed_state((self.id.clone(), "arc-rotation"), cx, |_, _| 0.);
110        if indeterminate == 1. || indeterminate == 0. {
111            let rotation = circular_segment.0.round();
112            if *loop_origin.read(cx) != rotation {
113                loop_origin.update(cx, |origin, _| *origin = rotation);
114            }
115        }
116        let start = (circular_segment.0 - *loop_origin.read(cx)) * indeterminate;
117        let extent = determinate + (circular_segment.1 - determinate) * indeterminate;
118        let segment = (start, start + extent);
119        let lines = if circular || indeterminate == 0. || reduced {
120            [(0.25, 0.65), (0., 0.)]
121        } else {
122            linear_indeterminate(elapsed)
123        };
124        let side = if circular {
125            if wavy { 48. } else { 40. }
126        } else if wavy {
127            10.
128        } else {
129            4.
130        };
131        let picture = canvas(
132            |_, _, _| (),
133            move |bounds, _, window, _| {
134                if circular {
135                    let center = bounds.center();
136                    let radius = (bounds.size.width.min(bounds.size.height)
137                        - px(if wavy { 8. } else { 4. }))
138                        / 2.;
139                    let sample = |fraction: f32, wave: bool| {
140                        let angle = (fraction - 0.25) * TAU;
141                        let radius = radius
142                            + px(if wave {
143                                1.6 * amplitude * ((fraction * 8. - wave_phase) * TAU).sin()
144                            } else {
145                                0.
146                            });
147                        center + point(radius * angle.cos(), radius * angle.sin())
148                    };
149                    // Round caps consume another stroke width around the 4 dp gap.
150                    let gap = (px(8.) / (radius * TAU)).clamp(0., 1.);
151                    if extent == 0. {
152                        stroke(0., 1., track, |f| sample(f, false), window);
153                    } else {
154                        stroke(
155                            segment.1 + gap,
156                            segment.0 + 1. - gap,
157                            track,
158                            |f| sample(f, false),
159                            window,
160                        );
161                    }
162                    stroke(segment.0, segment.1, active, |f| sample(f, wavy), window);
163                } else {
164                    let sample = |fraction: f32, wave: bool| {
165                        let from_start = if direction == Direction::Rtl {
166                            1. - fraction
167                        } else {
168                            fraction
169                        };
170                        let x = px(linear_position(f32::from(bounds.size.width), from_start));
171                        let wave = if wave {
172                            let wavelength = 40. - 20. * indeterminate;
173                            px(3.
174                                * amplitude
175                                * ((f32::from(x) / wavelength - wave_phase) * TAU).sin())
176                        } else {
177                            px(0.)
178                        };
179                        point(bounds.left() + x, bounds.center().y + wave)
180                    };
181                    let gap = (px(8.) / bounds.size.width.max(px(4.))).min(1.);
182                    let [first, second] = lines;
183                    let start = first.0 * indeterminate;
184                    let finish = determinate + (first.1 - determinate) * indeterminate;
185                    let second_end = second.0 + (second.1 - second.0) * indeterminate;
186                    let mut segments = [(start, finish), (second.0, second_end)];
187                    segments.sort_by(|left, right| left.0.total_cmp(&right.0));
188                    let mut position = 0.;
189                    for (start, finish) in segments {
190                        if finish <= start {
191                            continue;
192                        }
193                        stroke(position, start - gap, track, |f| sample(f, false), window);
194                        position = position.max(finish + gap);
195                    }
196                    stroke(position, 1., track, |f| sample(f, false), window);
197                    stroke(start, finish, active, |f| sample(f, wavy), window);
198                    if indeterminate > 0. {
199                        stroke(second.0, second_end, active, |f| sample(f, wavy), window);
200                    }
201                    if value.is_some() {
202                        let stop = point(
203                            bounds.left()
204                                + px(stop_position(f32::from(bounds.size.width), side, direction)),
205                            bounds.center().y,
206                        );
207                        window.paint_quad(gpui::quad(
208                            Bounds::from_corners(
209                                stop - point(px(2.), px(2.)),
210                                stop + point(px(2.), px(2.)),
211                            ),
212                            px(2.),
213                            active,
214                            px(0.),
215                            active,
216                            gpui::BorderStyle::Solid,
217                        ));
218                    }
219                }
220                if (animated || moving_wave && amplitude > 0.) && window.is_window_active() {
221                    window.request_animation_frame();
222                }
223            },
224        )
225        .size_full();
226        // Base owns the controlled numeric semantics; Material owns the drawing.
227        let mut element = gpui_base::Progress::new(self.id)
228            .value(value.unwrap_or_default() * 100.)
229            .indeterminate(value.is_none())
230            .accessibility_label(self.name)
231            .h(px(side))
232            .child(picture);
233        if circular {
234            element = element.w(px(side)).flex_none();
235        } else {
236            element = element.w_full();
237        }
238        element
239    }
240}
241
242// The keyframe timings match ProgressIndicator.kt in Material 3 1.5.0-rc01.
243fn linear_indeterminate(elapsed_ms: f32) -> [(f32, f32); 2] {
244    let clock = elapsed_ms % 1750.;
245    let sample = |delay, duration| {
246        easing_sample(
247            "md.sys.motion.easing-emphasized-accelerate",
248            (clock - delay) / duration,
249        )
250    };
251    [
252        (sample(250., 1000.), sample(0., 1000.)),
253        (sample(900., 850.), sample(650., 850.)),
254    ]
255}
256
257fn circular_indeterminate(elapsed_ms: f32) -> (f32, f32) {
258    let clock = elapsed_ms % 6000.;
259    let step = (clock / 1500.).floor();
260    let turn = easing_sample(
261        "md.sys.motion.easing-emphasized-decelerate",
262        (clock % 1500.) / 300.,
263    );
264    let phase = clock / 3000.;
265    let length = if phase < 1. {
266        0.1 + (0.87 - 0.1) * phase
267    } else {
268        0.87 - (0.87 - 0.1) * easing_sample("md.sys.motion.easing-standard", phase - 1.)
269    };
270    // Keep the angle unwrapped during a mode change, then paint it periodically.
271    (
272        (elapsed_ms / 6000.) * 3. + (elapsed_ms / 6000.).floor() + (step + turn) / 4.,
273        length,
274    )
275}
276
277fn easing_sample(name: &str, progress: f32) -> f32 {
278    let progress = progress.clamp(0., 1.);
279    let TokenValue::Easing(curve) = token(name).expect("bundled progress easing") else {
280        unreachable!("progress easing token must contain a cubic Bézier");
281    };
282    let easing =
283        Easing::cubic_bezier(curve.x1, curve.y1, curve.x2, curve.y2).expect("valid Material curve");
284    easing.sample(progress)
285}
286
287fn stroke(
288    start: f32,
289    end: f32,
290    tint: Hsla,
291    sample: impl Fn(f32) -> Point<Pixels>,
292    window: &mut Window,
293) {
294    if end <= start {
295        return;
296    }
297    let count = ((end - start) * 100.).ceil() as usize;
298    let mut path = PathBuilder::stroke(px(4.));
299    path.move_to(sample(start));
300    for ix in 1..=count {
301        path.line_to(sample(start + (end - start) * ix as f32 / count as f32));
302    }
303    if let Ok(path) = path.build() {
304        window.paint_path(path, tint);
305    }
306    // GPUI's path tessellator uses butt caps. Material uses round caps for
307    // all three presentations, with the same endpoints as the sampled path.
308    for center in [sample(start), sample(end)] {
309        window.paint_quad(gpui::quad(
310            Bounds::from_corners(
311                center - point(px(2.), px(2.)),
312                center + point(px(2.), px(2.)),
313            ),
314            px(2.),
315            tint,
316            px(0.),
317            tint,
318            gpui::BorderStyle::Solid,
319        ));
320    }
321}
322
323fn linear_position(width: f32, fraction: f32) -> f32 {
324    if width < 4. {
325        width * fraction
326    } else {
327        (width * fraction).clamp(2., width - 2.)
328    }
329}
330
331fn wave_amplitude(progress: f32) -> f32 {
332    // WavyProgressIndicatorDefaults.indicatorAmplitude suppresses waves at the
333    // beginning and end; only the change between these targets is animated.
334    f32::from(progress > 0.1 && progress < 0.95)
335}
336
337fn stop_position(width: f32, height: f32, direction: Direction) -> f32 {
338    let inset = 2. + ((height - 4.).max(0.) / 2.).min(4.);
339    if direction == Direction::Rtl {
340        inset.min(width / 2.)
341    } else {
342        (width - inset).max(width / 2.)
343    }
344}
345
346/// Horizontal progress. Supply a fraction from 0 to 1, or omit it for indeterminate progress.
347#[derive(IntoElement)]
348pub struct LinearProgress(Progress);
349
350/// Circular progress. Supply a fraction from 0 to 1, or omit it for indeterminate progress.
351#[derive(IntoElement)]
352pub struct CircularProgress(Progress);
353
354macro_rules! progress_api {
355    ($name:ident, $circular:literal) => {
356        impl $name {
357            pub fn new(id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
358                Self(Progress::new(id, name))
359            }
360
361            pub fn value(mut self, value: f32) -> Self {
362                self.0.value = Some(value);
363                self
364            }
365
366            pub fn shape(mut self, shape: ProgressShape) -> Self {
367                self.0.shape = shape;
368                self
369            }
370        }
371
372        impl RenderOnce for $name {
373            fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
374                self.0.paint($circular, window, cx)
375            }
376        }
377    };
378}
379
380progress_api!(LinearProgress, false);
381progress_api!(CircularProgress, true);
382
383/// Status for an operation with unknown duration. The parent removes the
384/// indicator when the operation settles or sets it inactive to retain its space.
385#[derive(IntoElement)]
386pub struct LoadingIndicator {
387    id: ElementId,
388    label: SharedString,
389    contained: bool,
390    active: bool,
391}
392
393impl LoadingIndicator {
394    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
395        Self {
396            id: id.into(),
397            label: label.into(),
398            contained: false,
399            active: true,
400        }
401    }
402
403    pub fn contained(mut self, contained: bool) -> Self {
404        self.contained = contained;
405        self
406    }
407
408    pub fn active(mut self, active: bool) -> Self {
409        self.active = active;
410        self
411    }
412}
413
414struct LoadingMotion {
415    epoch: Option<Instant>,
416    elapsed: Duration,
417    shapes: [Morph; 7],
418    scale: f32,
419}
420
421impl Default for LoadingMotion {
422    fn default() -> Self {
423        let shapes = [
424            shapes::soft_burst(),
425            shapes::cookie9(),
426            shapes::pentagon(),
427            shapes::pill(),
428            shapes::sunny(),
429            shapes::cookie4(),
430            shapes::oval(),
431        ];
432        Self {
433            epoch: None,
434            elapsed: Duration::ZERO,
435            scale: loading_scale(&shapes),
436            shapes: std::array::from_fn(|ix| {
437                Morph::new(
438                    shapes[ix].clone().normalized(),
439                    shapes[(ix + 1) % shapes.len()].clone().normalized(),
440                )
441            }),
442        }
443    }
444}
445
446// Compose LoadingIndicator.calculateScaleFactor and graphics-shapes
447// RoundedPolygon.calculateMaxBounds compare the ordinary bounds with the
448// rotation envelope sampled at each cubic's anchor and midpoint.
449fn loading_scale(shapes: &[polymorpher::RoundedPolygon]) -> f32 {
450    shapes.iter().fold(1., |scale, shape| {
451        let bounds = shape.aabb(true).size();
452        let radius = shape
453            .cubics
454            .iter()
455            .flat_map(|cubic| [cubic.anchor0(), cubic.point_on_curve(0.5)])
456            .map(|point| (point - shape.center).length())
457            .fold(0_f32, f32::max);
458        scale.min(bounds.width.max(bounds.height) / (2. * radius))
459    })
460}
461
462fn loading_center(cubics: &[polymorpher::Cubic]) -> polymorpher::geometry::Point {
463    let mut minimum = polymorpher::geometry::Point::new(f32::INFINITY, f32::INFINITY);
464    let mut maximum = polymorpher::geometry::Point::new(f32::NEG_INFINITY, f32::NEG_INFINITY);
465    for cubic in cubics {
466        let bounds = cubic.aabb(true);
467        minimum = minimum.min(bounds.min);
468        maximum = maximum.max(bounds.max);
469    }
470    polymorpher::geometry::Point::new((minimum.x + maximum.x) * 0.5, (minimum.y + maximum.y) * 0.5)
471}
472
473impl RenderOnce for LoadingIndicator {
474    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
475        let theme = window_material_theme(window, cx);
476        let fill = color(theme.colors.color(if self.contained {
477            ColorRole::OnPrimaryContainer
478        } else {
479            ColorRole::Primary
480        }));
481        let background = color(theme.colors.color(ColorRole::PrimaryContainer));
482        let reduced = cx.reduce_motion();
483        let animate = self.active && !reduced && window.is_window_active();
484        let now = cx.background_executor().now();
485        let motion = window.use_keyed_state(
486            ElementId::from((self.id.clone(), "loading-motion")),
487            cx,
488            |_, _| LoadingMotion::default(),
489        );
490        let progress = motion.update(cx, |state, _| {
491            if !self.active || reduced {
492                state.epoch = None;
493                state.elapsed = Duration::ZERO;
494                return 0.;
495            }
496            let elapsed = if animate {
497                state.elapsed + now.saturating_duration_since(*state.epoch.get_or_insert(now))
498            } else {
499                if let Some(epoch) = state.epoch.take() {
500                    state.elapsed += now.saturating_duration_since(epoch);
501                }
502                state.elapsed
503            };
504            elapsed.as_secs_f32() / 0.65
505        });
506        let icon = canvas(
507            |_, _, _| (),
508            move |bounds, _, window, cx| {
509                let state = motion.read(cx);
510                let bounds = Bounds::from_corners(
511                    bounds.origin + point(px(5.), px(5.)),
512                    bounds.bottom_right() - point(px(5.), px(5.)),
513                );
514                let phase = progress.fract();
515                let spring_time = phase * 0.65;
516                let frequency = 200_f32.sqrt();
517                let decay = 0.6 * frequency;
518                let damped_frequency = frequency * 0.8;
519                let t = damped_frequency * spring_time;
520                let eased =
521                    (1. - (-decay * spring_time).exp() * (t.cos() + 0.75 * t.sin())).clamp(0., 1.);
522                let index = progress.floor() as usize % state.shapes.len();
523                let cubics = state.shapes[index].as_cubics(eased);
524                // Compose processPath centers the current path, not the endpoints'
525                // original unit square; asymmetric intermediate morphs can drift.
526                let center = loading_center(&cubics);
527                let angle = (progress * 0.65 / 4.666 + (1. + progress.floor() + eased) / 4.) * TAU;
528                let (sin, cos) = angle.sin_cos();
529                let project = |p: polymorpher::geometry::Point| {
530                    let x = p.x - center.x;
531                    let y = p.y - center.y;
532                    bounds.center()
533                        + point(
534                            bounds.size.width * state.scale * (cos * x - sin * y),
535                            bounds.size.height * state.scale * (sin * x + cos * y),
536                        )
537                };
538                if let Some(first) = cubics.first() {
539                    let mut path = PathBuilder::fill();
540                    path.move_to(project(first.anchor0()));
541                    for cubic in cubics {
542                        path.cubic_bezier_to(
543                            project(cubic.anchor1()),
544                            project(cubic.control0()),
545                            project(cubic.control1()),
546                        );
547                    }
548                    path.close();
549                    if let Ok(path) = path.build() {
550                        window.paint_path(path, fill);
551                    }
552                }
553                if animate {
554                    window.request_animation_frame();
555                }
556            },
557        )
558        .size_full();
559        let element = div().size(px(48.)).flex_none();
560        if self.active {
561            let mut progress = gpui_base::Progress::new(self.id)
562                .indeterminate(true)
563                .accessibility_label(self.label)
564                .size(px(48.))
565                .flex_none()
566                .a11y_synthetic_children(|node| {
567                    node.parent_node().set_live(gpui::accesskit::Live::Polite);
568                    node.parent_node().set_live_atomic();
569                })
570                .child(icon);
571            if self.contained {
572                progress = progress.rounded_full().bg(background);
573            }
574            progress.into_any_element()
575        } else {
576            element.id(self.id).into_any_element()
577        }
578    }
579}
580
581#[cfg(test)]
582mod tests {
583    use super::*;
584
585    #[test]
586    fn loading_shapes_fit_the_active_size_through_rotation_and_morphs() {
587        let motion = LoadingMotion::default();
588        assert!(motion.scale > 0. && motion.scale < 1.);
589        for morph in &motion.shapes {
590            for step in 0..=20 {
591                let cubics = morph.as_cubics(step as f32 / 20.);
592                let center = loading_center(&cubics);
593                for cubic in cubics {
594                    for sample in 0..=20 {
595                        let p = cubic.point_on_curve(sample as f32 / 20.);
596                        let radius = (p.x - center.x).hypot(p.y - center.y) * motion.scale;
597                        // All rotation angles are bounded by the radial envelope.
598                        assert!(
599                            radius <= 0.501,
600                            "active shape escapes its 38 dp envelope: {radius}"
601                        );
602                    }
603                }
604            }
605        }
606    }
607
608    #[test]
609    fn rounded_progress_endpoints_and_stop_stay_inside_the_track() {
610        assert_eq!(linear_position(100., 0.), 2.);
611        assert_eq!(linear_position(100., 1.), 98.);
612        assert_eq!(linear_position(100., 0.5), 50.);
613        for height in [4., 10.] {
614            let ltr = stop_position(100., height, Direction::Ltr);
615            let rtl = stop_position(100., height, Direction::Rtl);
616            assert_eq!(ltr + rtl, 100.);
617            assert!(ltr + 2. <= 100. && rtl - 2. >= 0.);
618        }
619        assert_eq!(stop_position(100., 4., Direction::Ltr), 98.);
620        assert_eq!(stop_position(100., 10., Direction::Ltr), 95.);
621    }
622
623    #[test]
624    fn determinate_wave_is_flat_at_both_ends_of_the_range() {
625        for value in [0., 0.05, 0.1, 0.95, 0.99, 1.] {
626            assert_eq!(wave_amplitude(value), 0.);
627        }
628        for value in [0.11, 0.5, 0.94] {
629            assert_eq!(wave_amplitude(value), 1.);
630        }
631    }
632
633    #[test]
634    fn indeterminate_keyframes_use_both_linear_segments_and_periodic_rotation() {
635        assert_eq!(linear_indeterminate(0.), [(0., 0.); 2]);
636        let [(start, end), (second_start, second_end)] = linear_indeterminate(800.);
637        assert!(0. < start && start < end && end < 1.);
638        assert_eq!(second_start, 0.);
639        assert!(second_end > 0.);
640        assert_eq!(linear_indeterminate(2550.), linear_indeterminate(800.));
641        assert_eq!(circular_indeterminate(0.), (0., 0.1));
642        assert_eq!(circular_indeterminate(6000.), (4., 0.1));
643        assert_eq!(circular_indeterminate(3000.).1, 0.87);
644    }
645}