Skip to main content

gpui_material_components/
loading_indicator.rs

1//! Loading indicators and rounded polygon constructors for custom sequences.
2
3use std::{f32::consts::TAU, rc::Rc, sync::LazyLock};
4
5use gpui::{
6    App, Bounds, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement, Path, Pixels,
7    Point, RenderOnce, SharedString, StatefulInteractiveElement, Styled, Window, canvas, div, px,
8};
9use gpui_material_foundation::{
10    LoopClock, ShapeMorphSequence, ShapePolygon, color, current_material_theme, is_bounds_visible,
11};
12use gpui_material_theme::{ColorRole, CornerShape, MaterialShape};
13use web_time::Instant;
14
15const CONTAINER_SIZE: f32 = 48.;
16const ACTIVE_SIZE: f32 = 38.;
17const MORPH_INTERVAL: f32 = 0.65;
18
19static INDETERMINATE_SHAPES: LazyLock<ShapeMorphSequence> = LazyLock::new(|| {
20    ShapeMorphSequence::new(
21        [
22            MaterialShape::SoftBurst,
23            MaterialShape::Cookie9Sided,
24            MaterialShape::Pentagon,
25            MaterialShape::Pill,
26            MaterialShape::Sunny,
27            MaterialShape::Cookie4Sided,
28            MaterialShape::Oval,
29        ],
30        true,
31    )
32    .expect("default indeterminate loading sequence has seven shapes")
33});
34
35static DETERMINATE_SHAPES: LazyLock<ShapeMorphSequence> = LazyLock::new(|| {
36    let circle = ShapePolygon::circle(10)
37        .expect("10-vertex circle is valid")
38        .rotated(18.);
39    ShapeMorphSequence::new(
40        [circle, ShapePolygon::material(MaterialShape::SoftBurst)],
41        false,
42    )
43    .expect("default determinate loading sequence has two shapes")
44});
45
46/// An endpoint shape for a loading indicator morph.
47#[derive(Clone, Debug, PartialEq)]
48pub struct LoadingIndicatorShape(ShapePolygon);
49
50impl LoadingIndicatorShape {
51    /// Creates a circular morph endpoint (`MaterialShape::Circle`).
52    pub fn circle() -> Self {
53        Self(ShapePolygon::material(MaterialShape::Circle))
54    }
55
56    /// Uses one of the 35 Material 3 Expressive shapes as a morph endpoint.
57    pub fn material(shape: MaterialShape) -> Self {
58        Self(ShapePolygon::material(shape))
59    }
60
61    /// Creates a rounded polygon from its perimeter vertices in either winding order.
62    /// The radius uses the same units as the vertices. Invalid geometry returns `None`.
63    pub fn rounded_polygon(vertices: &[Point<f32>], radius: f32) -> Option<Self> {
64        ShapePolygon::from_vertices(vertices, radius).map(Self)
65    }
66}
67
68impl From<MaterialShape> for LoadingIndicatorShape {
69    fn from(shape: MaterialShape) -> Self {
70        Self::material(shape)
71    }
72}
73
74impl From<ShapePolygon> for LoadingIndicatorShape {
75    fn from(polygon: ShapePolygon) -> Self {
76        Self(polygon)
77    }
78}
79
80/// A prepared sequence of rounded polygons for a loading indicator.
81#[derive(Clone)]
82pub struct LoadingIndicatorShapes(Rc<ShapeMorphSequence>);
83
84impl LoadingIndicatorShapes {
85    /// Returns `None` when the sequence contains fewer than two shapes.
86    pub fn new(shapes: impl IntoIterator<Item = LoadingIndicatorShape>) -> Option<Self> {
87        let polygons = shapes.into_iter().map(|shape| shape.0);
88        ShapeMorphSequence::perimeter_aligned(polygons, true).map(|seq| Self(Rc::new(seq)))
89    }
90}
91
92/// Progress for an operation. Pass a value to select determinate mode, or omit
93/// the value for an indeterminate animation.
94#[derive(IntoElement)]
95pub struct LoadingIndicator {
96    id: ElementId,
97    label: SharedString,
98    contained: bool,
99    active: bool,
100    value: Option<f32>,
101    shapes: Option<LoadingIndicatorShapes>,
102    indicator_color: Option<Hsla>,
103    container_color: Option<Hsla>,
104    container_shape: CornerShape,
105}
106
107impl LoadingIndicator {
108    /// Creates an active, indeterminate loading indicator with the given element ID and accessible label.
109    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
110        Self {
111            id: id.into(),
112            label: label.into(),
113            contained: false,
114            active: true,
115            value: None,
116            shapes: None,
117            indicator_color: None,
118            container_color: None,
119            container_shape: CornerShape::Full,
120        }
121    }
122
123    /// Wraps the morphing shape in a filled `PrimaryContainer` background when `true`. Defaults to `false`.
124    pub fn contained(mut self, contained: bool) -> Self {
125        self.contained = contained;
126        self
127    }
128
129    /// Retains the footprint when inactive and suppresses paint and progress semantics.
130    pub fn active(mut self, active: bool) -> Self {
131        self.active = active;
132        self
133    }
134
135    /// Sets caller-owned progress. The fraction is clamped to `0..=1`. NaN means zero.
136    pub fn value(mut self, value: f32) -> Self {
137        self.value = Some(if value.is_nan() {
138            0.
139        } else {
140            value.clamp(0., 1.)
141        });
142        self
143    }
144
145    /// Uses a prepared shape sequence for either progress mode.
146    pub fn shapes(mut self, shapes: &LoadingIndicatorShapes) -> Self {
147        self.shapes = Some(shapes.clone());
148        self
149    }
150
151    /// Overrides the shape fill in either variant.
152    pub fn indicator_color(mut self, color: impl Into<Hsla>) -> Self {
153        self.indicator_color = Some(color.into());
154        self
155    }
156
157    /// Overrides the background fill of a contained indicator.
158    pub fn container_color(mut self, color: impl Into<Hsla>) -> Self {
159        self.container_color = Some(color.into());
160        self
161    }
162
163    /// Sets logical corner radii for the contained indicator's background.
164    pub fn container_shape(mut self, shape: CornerShape) -> Self {
165        self.container_shape = shape;
166        self
167    }
168}
169
170impl RenderOnce for LoadingIndicator {
171    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
172        let container_size = px(CONTAINER_SIZE);
173        if !self.active {
174            return div()
175                .id(self.id)
176                .size(container_size)
177                .flex_none()
178                .into_any_element();
179        }
180
181        let theme = current_material_theme(window, cx);
182        let fill = self.indicator_color.unwrap_or_else(|| {
183            color(theme.colors.color(if self.contained {
184                ColorRole::OnPrimaryContainer
185            } else {
186                ColorRole::Primary
187            }))
188        });
189        let background = self
190            .container_color
191            .unwrap_or_else(|| color(theme.colors.color(ColorRole::PrimaryContainer)));
192        let radii =
193            self.container_shape
194                .radii(CONTAINER_SIZE, CONTAINER_SIZE, theme.layout.direction);
195        let active_size = if self.contained {
196            // A radius greater than half the side can arc into the centered
197            // indicator. Fit the active shape into the largest centered disk.
198            let radius = radii.into_iter().fold(CONTAINER_SIZE * 0.5, f32::max);
199            ACTIVE_SIZE.min(2. * (radius - (radius - CONTAINER_SIZE * 0.5) * 2_f32.sqrt()))
200        } else {
201            ACTIVE_SIZE
202        };
203        let reduced = cx.reduce_motion();
204        let running =
205            self.value.is_none() && !reduced && window.is_window_active() && window.is_visible();
206        let motion = self.value.is_none().then(|| {
207            window.use_keyed_state((self.id.clone(), "loading-motion"), cx, |_, _| {
208                IndeterminateMotion::default()
209            })
210        });
211        let phase = if let Some(motion) = &motion {
212            let now = cx.background_executor().now();
213            motion.update(cx, |state, _| {
214                state.phase(now, running && state.visible, reduced)
215            })
216        } else {
217            0.
218        };
219        let icon = canvas(
220            |_, _, _| (),
221            move |bounds, _, window, cx| {
222                let visible = is_bounds_visible(bounds, window);
223                if let Some(motion) = &motion {
224                    let now = cx.background_executor().now();
225                    motion.update(cx, |state, _| {
226                        state.set_visible(visible, now);
227                    });
228                }
229                if !visible {
230                    return;
231                }
232                let shapes = self.shapes.as_ref().map_or_else(
233                    || {
234                        if self.value.is_some() {
235                            &*DETERMINATE_SHAPES
236                        } else {
237                            &*INDETERMINATE_SHAPES
238                        }
239                    },
240                    |shapes| &*shapes.0,
241                );
242                let sample = match self.value {
243                    Some(value) => determinate_sample(shapes, value),
244                    None => indeterminate_sample(shapes, phase),
245                };
246                if let Some(path) = sample.path(bounds, active_size, shapes) {
247                    window.paint_path(path, fill);
248                }
249                if running {
250                    window.request_animation_frame();
251                }
252            },
253        )
254        .size_full();
255        let mut control = progress_node(self.id, self.label, self.value)
256            .size(container_size)
257            .flex_none()
258            .child(icon);
259        if self.contained {
260            let [tl, tr, br, bl] = radii.map(px);
261            control = control
262                .rounded_tl(tl)
263                .rounded_tr(tr)
264                .rounded_br(br)
265                .rounded_bl(bl)
266                .bg(background);
267        }
268        control.into_any_element()
269    }
270}
271
272fn progress_node(id: ElementId, label: SharedString, value: Option<f32>) -> gpui_base::Progress {
273    let control = gpui_base::Progress::new(id).accessibility_label(label);
274    match value {
275        Some(value) => control.value(value * 100.),
276        None => control.indeterminate(true).a11y_synthetic_children(|node| {
277            node.parent_node().set_live(gpui::accesskit::Live::Polite);
278            node.parent_node().set_live_atomic();
279        }),
280    }
281}
282
283struct IndeterminateMotion {
284    clock: LoopClock,
285    visible: bool,
286}
287
288impl Default for IndeterminateMotion {
289    fn default() -> Self {
290        Self {
291            clock: LoopClock::default(),
292            visible: true,
293        }
294    }
295}
296
297impl IndeterminateMotion {
298    fn set_visible(&mut self, visible: bool, now: Instant) {
299        if self.visible != visible {
300            self.visible = visible;
301            if !visible {
302                self.clock.pause(now);
303            }
304        }
305    }
306
307    fn phase(&mut self, now: Instant, running: bool, reduced: bool) -> f32 {
308        self.clock.advance(now, running, reduced).as_secs_f32() / MORPH_INTERVAL
309    }
310}
311
312struct MorphSample {
313    step: usize,
314    progress: f32,
315    angle: f32,
316}
317
318fn determinate_sample(sequence: &ShapeMorphSequence, value: f32) -> MorphSample {
319    let open_steps = sequence.len() - 1;
320    let phase = value * open_steps as f32;
321    let step = (phase as usize).min(open_steps - 1);
322    MorphSample {
323        step,
324        progress: phase - step as f32,
325        angle: -value * TAU * 0.5,
326    }
327}
328
329fn indeterminate_sample(sequence: &ShapeMorphSequence, phase: f32) -> MorphSample {
330    let count = sequence.step_count();
331    let step_floor = phase.floor();
332    let step = step_floor as usize % count;
333    let time = phase.fract() * MORPH_INTERVAL;
334    let frequency = 200_f32.sqrt();
335    let damped = frequency * 0.8 * time;
336    let progress =
337        (1. - (-0.6 * frequency * time).exp() * (damped.cos() + 0.75 * damped.sin())).clamp(0., 1.);
338    MorphSample {
339        step,
340        progress,
341        angle: (phase * MORPH_INTERVAL / 4.666 + (1. + step_floor + progress) / 4.) * TAU,
342    }
343}
344
345impl MorphSample {
346    fn path(
347        self,
348        bounds: Bounds<Pixels>,
349        extent: f32,
350        sequence: &ShapeMorphSequence,
351    ) -> Option<Path<Pixels>> {
352        sequence
353            .sample_step_in_envelope(self.step, self.progress, bounds, px(extent), self.angle)
354            .map(|shape| shape.fill_path().clone())
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use std::time::Duration;
361
362    use super::*;
363    use gpui::{point, size};
364
365    #[test]
366    fn loading_shapes_fit_the_active_size_through_rotation_and_morphs() {
367        let shape_sets = [&*INDETERMINATE_SHAPES, &*DETERMINATE_SHAPES];
368        let bounds = Bounds::new(point(px(0.), px(0.)), size(px(48.), px(48.)));
369        for shapes in shape_sets {
370            let scale = shapes.rotation_scale();
371            assert!(scale > 0. && scale <= 1.);
372            for step in 0..shapes.step_count() {
373                for tick in 0..=20 {
374                    let progress = tick as f32 / 20.;
375                    let sampled = shapes
376                        .sample_step_in_envelope(step, progress, bounds, px(ACTIVE_SIZE), 0.)
377                        .unwrap();
378                    assert!(sampled.fill_path().vertices.iter().all(|v| {
379                        let delta = v.xy_position - bounds.center();
380                        f32::from(delta.x).hypot(f32::from(delta.y)) <= ACTIVE_SIZE * 0.5 + 0.05
381                    }));
382                }
383            }
384        }
385    }
386
387    #[test]
388    fn determinate_progress_handles_numeric_boundaries() {
389        for (input, expected) in [
390            (f32::NAN, 0.),
391            (f32::NEG_INFINITY, 0.),
392            (-0.1, 0.),
393            (0.5, 0.5),
394            (1.1, 1.),
395            (f32::INFINITY, 1.),
396        ] {
397            assert_eq!(
398                LoadingIndicator::new("loading", "Loading")
399                    .value(input)
400                    .value,
401                Some(expected)
402            );
403        }
404        let shapes = &*DETERMINATE_SHAPES;
405        let bounds = Bounds::new(point(px(0.), px(0.)), size(px(48.), px(48.)));
406        let start = determinate_sample(shapes, 0.);
407        let end = determinate_sample(shapes, 1.);
408        assert_eq!((start.progress, start.angle), (0., 0.));
409        assert_eq!((end.progress, end.angle), (1., -TAU * 0.5));
410        let start_path = start.path(bounds, ACTIVE_SIZE, shapes).unwrap();
411        let end_path = end.path(bounds, ACTIVE_SIZE, shapes).unwrap();
412        assert_ne!(start_path.vertices.len(), end_path.vertices.len());
413    }
414
415    #[test]
416    fn a_custom_sequence_morphs_between_endpoints_and_wraps_only_when_indeterminate() {
417        let rectangle = |w, h| {
418            LoadingIndicatorShape::rounded_polygon(
419                &[point(0., 0.), point(w, 0.), point(w, h), point(0., h)],
420                0.,
421            )
422            .unwrap()
423        };
424        let custom = LoadingIndicatorShapes::new([
425            rectangle(2., 1.),
426            LoadingIndicatorShape::circle(),
427            rectangle(1., 2.),
428        ])
429        .unwrap();
430        let shapes = &custom.0;
431        let bounds = Bounds::new(point(px(0.), px(0.)), size(px(48.), px(48.)));
432        let frame = |value| {
433            determinate_sample(shapes, value)
434                .path(bounds, ACTIVE_SIZE, shapes)
435                .unwrap()
436                .bounds
437                .size
438        };
439        let start = frame(0.);
440        let middle = frame(0.5);
441        let end = frame(1.);
442        assert!((start.width / start.height - 2.).abs() < 0.05);
443        assert!((middle.width / middle.height - 1.).abs() < 0.05);
444        assert!((end.height / end.width - 2.).abs() < 0.05);
445        for value in [0.4999, 0.5001] {
446            let adjacent = frame(value);
447            assert!((adjacent.width - middle.width).abs() < px(0.05));
448            assert!((adjacent.height - middle.height).abs() < px(0.05));
449        }
450        let first = indeterminate_sample(shapes, 0.);
451        let wrap = indeterminate_sample(shapes, 2.);
452        let repeated = indeterminate_sample(shapes, 3.);
453        assert_eq!(first.step, 0);
454        assert_eq!(wrap.step, 2);
455        assert_eq!(repeated.step, 0);
456        assert_eq!(
457            (first.progress, wrap.progress, repeated.progress),
458            (0., 0., 0.)
459        );
460    }
461
462    #[test]
463    fn custom_concave_paths_align_winding_and_fit_the_active_envelope() {
464        let mut vertices = [
465            point(-1., -1.),
466            point(1., -1.),
467            point(0., 0.),
468            point(1., 1.),
469            point(-1., 1.),
470        ];
471        let polygon = LoadingIndicatorShape::rounded_polygon(&vertices, 0.1).unwrap();
472        vertices.reverse();
473        let reversed = LoadingIndicatorShape::rounded_polygon(&vertices, 0.1).unwrap();
474        assert_eq!(polygon, reversed);
475        let circle = LoadingIndicatorShape::circle();
476        let limit = polygon.0.cubic_count() + circle.0.cubic_count();
477        let sequence = LoadingIndicatorShapes::new([polygon, circle]).unwrap();
478        let shapes = &sequence.0;
479        let bounds = Bounds::new(point(px(0.), px(0.)), size(px(48.), px(48.)));
480        for step in 0..=20 {
481            let sample = determinate_sample(shapes, step as f32 / 20.);
482            let outline = shapes
483                .sample_step_polygon(sample.step, sample.progress)
484                .unwrap();
485            assert!(outline.cubic_count() < limit);
486            let path = sample.path(bounds, ACTIVE_SIZE, shapes).unwrap();
487            assert!(path.vertices.iter().all(|point| {
488                let delta = point.xy_position - bounds.center();
489                f32::from(delta.x).hypot(delta.y.into()) <= ACTIVE_SIZE * 0.5 + 0.05
490            }));
491        }
492    }
493
494    #[test]
495    fn expressive_material_shapes_work_in_loading_indicator_sequences() {
496        let sequence = LoadingIndicatorShapes::new([
497            LoadingIndicatorShape::material(MaterialShape::Heart),
498            LoadingIndicatorShape::from(MaterialShape::Cookie12Sided),
499            LoadingIndicatorShape::from(ShapePolygon::material(MaterialShape::Clover4Leaf)),
500        ])
501        .unwrap();
502        let bounds = Bounds::new(point(px(0.), px(0.)), size(px(48.), px(48.)));
503        let path = determinate_sample(&sequence.0, 0.5)
504            .path(bounds, ACTIVE_SIZE, &sequence.0)
505            .unwrap();
506        assert!(!path.vertices.is_empty());
507    }
508
509    #[test]
510    fn rejects_short_and_degenerate_shape_sequences() {
511        assert!(LoadingIndicatorShapes::new([]).is_none());
512        assert!(LoadingIndicatorShapes::new([LoadingIndicatorShape::circle()]).is_none());
513        for outline in [
514            &[point(0., 0.), point(0., 0.), point(0., 0.)][..],
515            &[point(0., 0.), point(1., 1.), point(2., 2.)],
516            &[point(0., 0.), point(1., 1.), point(1., 0.), point(0., 1.)],
517            &[point(0., 0.), point(f32::INFINITY, 0.), point(2., 2.)],
518        ] {
519            assert!(LoadingIndicatorShape::rounded_polygon(outline, 0.).is_none());
520        }
521        for radius in [f32::NAN, -1.] {
522            assert!(
523                LoadingIndicatorShape::rounded_polygon(
524                    &[point(0., 0.), point(1., 0.), point(1., 1.)],
525                    radius,
526                )
527                .is_none()
528            );
529        }
530    }
531
532    #[test]
533    fn indeterminate_phase_pauses_and_reduced_motion_holds_the_start() {
534        let mut motion = IndeterminateMotion::default();
535        let start = Instant::now();
536        let after = |millis| start + Duration::from_millis(millis);
537        assert_eq!(motion.phase(start, true, false), 0.);
538        let paused = motion.phase(after(200), false, false);
539        assert!(paused > 0.);
540        assert_eq!(motion.phase(after(400), false, false), paused);
541        assert_eq!(motion.phase(after(550), true, false), paused);
542        assert!(motion.phase(after(700), true, false) > paused);
543        assert_eq!(motion.phase(after(800), false, true), 0.);
544        assert_eq!(motion.phase(after(950), false, true), 0.);
545        assert_eq!(motion.phase(after(1050), true, false), 0.);
546    }
547}