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