1use 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#[derive(Clone, Debug, PartialEq)]
48pub struct LoadingIndicatorShape(ShapePolygon);
49
50impl LoadingIndicatorShape {
51 pub fn circle() -> Self {
53 Self(ShapePolygon::material(MaterialShape::Circle))
54 }
55
56 pub fn material(shape: MaterialShape) -> Self {
58 Self(ShapePolygon::material(shape))
59 }
60
61 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#[derive(Clone)]
82pub struct LoadingIndicatorShapes(Rc<ShapeMorphSequence>);
83
84impl LoadingIndicatorShapes {
85 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#[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 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 pub fn contained(mut self, contained: bool) -> Self {
125 self.contained = contained;
126 self
127 }
128
129 pub fn active(mut self, active: bool) -> Self {
131 self.active = active;
132 self
133 }
134
135 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 pub fn shapes(mut self, shapes: &LoadingIndicatorShapes) -> Self {
147 self.shapes = Some(shapes.clone());
148 self
149 }
150
151 pub fn indicator_color(mut self, color: impl Into<Hsla>) -> Self {
153 self.indicator_color = Some(color.into());
154 self
155 }
156
157 pub fn container_color(mut self, color: impl Into<Hsla>) -> Self {
159 self.container_color = Some(color.into());
160 self
161 }
162
163 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 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> {
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.contains(bounds.center()));
379 let outer_radius = ACTIVE_SIZE * 0.5 + 0.1;
380 for sample in 0..36 {
381 let angle = std::f32::consts::TAU * sample as f32 / 36.;
382 let outside = bounds.center()
383 + point(
384 px(outer_radius * angle.cos()),
385 px(outer_radius * angle.sin()),
386 );
387 assert!(!sampled.contains(outside));
388 }
389 }
390 }
391 }
392 }
393
394 #[test]
395 fn determinate_progress_handles_numeric_boundaries() {
396 for (input, expected) in [
397 (f32::NAN, 0.),
398 (f32::NEG_INFINITY, 0.),
399 (-0.1, 0.),
400 (0.5, 0.5),
401 (1.1, 1.),
402 (f32::INFINITY, 1.),
403 ] {
404 assert_eq!(
405 LoadingIndicator::new("loading", "Loading")
406 .value(input)
407 .value,
408 Some(expected)
409 );
410 }
411 let shapes = &*DETERMINATE_SHAPES;
412 let bounds = Bounds::new(point(px(0.), px(0.)), size(px(48.), px(48.)));
413 let start = determinate_sample(shapes, 0.);
414 let end = determinate_sample(shapes, 1.);
415 assert_eq!((start.progress, start.angle), (0., 0.));
416 assert_eq!((end.progress, end.angle), (1., -TAU * 0.5));
417 let start_shape = shapes
418 .sample_step_in_envelope(
419 start.step,
420 start.progress,
421 bounds,
422 px(ACTIVE_SIZE),
423 start.angle,
424 )
425 .unwrap();
426 let end_shape = shapes
427 .sample_step_in_envelope(end.step, end.progress, bounds, px(ACTIVE_SIZE), end.angle)
428 .unwrap();
429 assert_ne!(start_shape.fill_bounds(), end_shape.fill_bounds());
430 }
431
432 #[test]
433 fn a_custom_sequence_morphs_between_endpoints_and_wraps_only_when_indeterminate() {
434 let rectangle = |w, h| {
435 LoadingIndicatorShape::rounded_polygon(
436 &[point(0., 0.), point(w, 0.), point(w, h), point(0., h)],
437 0.,
438 )
439 .unwrap()
440 };
441 let custom = LoadingIndicatorShapes::new([
442 rectangle(2., 1.),
443 LoadingIndicatorShape::circle(),
444 rectangle(1., 2.),
445 ])
446 .unwrap();
447 let shapes = &custom.0;
448 let bounds = Bounds::new(point(px(0.), px(0.)), size(px(48.), px(48.)));
449 let frame = |value| {
450 let sample = determinate_sample(shapes, value);
451 shapes
452 .sample_step_in_envelope(
453 sample.step,
454 sample.progress,
455 bounds,
456 px(ACTIVE_SIZE),
457 sample.angle,
458 )
459 .unwrap()
460 .fill_bounds()
461 .size
462 };
463 let start = frame(0.);
464 let middle = frame(0.5);
465 let end = frame(1.);
466 assert!((start.width / start.height - 2.).abs() < 0.05);
467 assert!((middle.width / middle.height - 1.).abs() < 0.05);
468 assert!((end.height / end.width - 2.).abs() < 0.05);
469 for value in [0.4999, 0.5001] {
470 let adjacent = frame(value);
471 assert!((adjacent.width - middle.width).abs() < px(0.05));
472 assert!((adjacent.height - middle.height).abs() < px(0.05));
473 }
474 let first = indeterminate_sample(shapes, 0.);
475 let wrap = indeterminate_sample(shapes, 2.);
476 let repeated = indeterminate_sample(shapes, 3.);
477 assert_eq!(first.step, 0);
478 assert_eq!(wrap.step, 2);
479 assert_eq!(repeated.step, 0);
480 assert_eq!(
481 (first.progress, wrap.progress, repeated.progress),
482 (0., 0., 0.)
483 );
484 }
485
486 #[test]
487 fn custom_concave_paths_align_winding_and_fit_the_active_envelope() {
488 let mut vertices = [
489 point(-1., -1.),
490 point(1., -1.),
491 point(0., 0.),
492 point(1., 1.),
493 point(-1., 1.),
494 ];
495 let polygon = LoadingIndicatorShape::rounded_polygon(&vertices, 0.1).unwrap();
496 vertices.reverse();
497 let reversed = LoadingIndicatorShape::rounded_polygon(&vertices, 0.1).unwrap();
498 assert_eq!(polygon, reversed);
499 let circle = LoadingIndicatorShape::circle();
500 let limit = polygon.0.cubic_count() + circle.0.cubic_count();
501 let sequence = LoadingIndicatorShapes::new([polygon, circle]).unwrap();
502 let shapes = &sequence.0;
503 let bounds = Bounds::new(point(px(0.), px(0.)), size(px(48.), px(48.)));
504 for step in 0..=20 {
505 let sample = determinate_sample(shapes, step as f32 / 20.);
506 let outline = shapes
507 .sample_step_polygon(sample.step, sample.progress)
508 .unwrap();
509 assert!(outline.cubic_count() < limit);
510 let shape = shapes
511 .sample_step_in_envelope(
512 sample.step,
513 sample.progress,
514 bounds,
515 px(ACTIVE_SIZE),
516 sample.angle,
517 )
518 .unwrap();
519 let outer_radius = ACTIVE_SIZE * 0.5 + 0.1;
520 for i in 0..36 {
521 let angle = TAU * i as f32 / 36.;
522 let outside = bounds.center()
523 + point(
524 px(outer_radius * angle.cos()),
525 px(outer_radius * angle.sin()),
526 );
527 assert!(!shape.contains(outside));
528 }
529 }
530 }
531
532 #[test]
533 fn expressive_material_shapes_work_in_loading_indicator_sequences() {
534 let sequence = LoadingIndicatorShapes::new([
535 LoadingIndicatorShape::material(MaterialShape::Heart),
536 LoadingIndicatorShape::from(MaterialShape::Cookie12Sided),
537 LoadingIndicatorShape::from(ShapePolygon::material(MaterialShape::Clover4Leaf)),
538 ])
539 .unwrap();
540 let bounds = Bounds::new(point(px(0.), px(0.)), size(px(48.), px(48.)));
541 let sample = determinate_sample(&sequence.0, 0.5);
542 let shape = sequence
543 .0
544 .sample_step_in_envelope(
545 sample.step,
546 sample.progress,
547 bounds,
548 px(ACTIVE_SIZE),
549 sample.angle,
550 )
551 .unwrap();
552 assert!(sample.path(bounds, ACTIVE_SIZE, &sequence.0).is_some());
553 assert!(shape.contains(bounds.center()));
554 }
555
556 #[test]
557 fn rejects_short_and_degenerate_shape_sequences() {
558 assert!(LoadingIndicatorShapes::new([]).is_none());
559 assert!(LoadingIndicatorShapes::new([LoadingIndicatorShape::circle()]).is_none());
560 for outline in [
561 &[point(0., 0.), point(0., 0.), point(0., 0.)][..],
562 &[point(0., 0.), point(1., 1.), point(2., 2.)],
563 &[point(0., 0.), point(1., 1.), point(1., 0.), point(0., 1.)],
564 &[point(0., 0.), point(f32::INFINITY, 0.), point(2., 2.)],
565 ] {
566 assert!(LoadingIndicatorShape::rounded_polygon(outline, 0.).is_none());
567 }
568 for radius in [f32::NAN, -1.] {
569 assert!(
570 LoadingIndicatorShape::rounded_polygon(
571 &[point(0., 0.), point(1., 0.), point(1., 1.)],
572 radius,
573 )
574 .is_none()
575 );
576 }
577 }
578
579 #[test]
580 fn indeterminate_phase_pauses_and_reduced_motion_holds_the_start() {
581 let mut motion = IndeterminateMotion::default();
582 let start = Instant::now();
583 let after = |millis| start + Duration::from_millis(millis);
584 assert_eq!(motion.phase(start, true, false), 0.);
585 let paused = motion.phase(after(200), false, false);
586 assert!(paused > 0.);
587 assert_eq!(motion.phase(after(400), false, false), paused);
588 assert_eq!(motion.phase(after(550), true, false), paused);
589 assert!(motion.phase(after(700), true, false) > paused);
590 assert_eq!(motion.phase(after(800), false, true), 0.);
591 assert_eq!(motion.phase(after(950), false, true), 0.);
592 assert_eq!(motion.phase(after(1050), true, false), 0.);
593 }
594}