1use std::{f32::consts::TAU, rc::Rc, sync::LazyLock, time::Duration};
4
5use gpui::{
6 App, Bounds, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement, Path,
7 PathBuilder, Pixels, Point, RenderOnce, SharedString, StatefulInteractiveElement, Styled,
8 Window, canvas, div, point, px,
9};
10use gpui_material_foundation::{color, window_material_theme};
11use gpui_material_theme::{ColorRole, CornerShape};
12use polymorpher::{
13 CornerRounding, Cubic, Morph, RoundedPolygon, geometry::Point as PolygonPoint, shapes,
14};
15use web_time::Instant;
16
17const CONTAINER_SIZE: f32 = 48.;
18const ACTIVE_SIZE: f32 = 38.;
19const MORPH_INTERVAL: f32 = 0.65;
20
21static INDETERMINATE_SHAPES: LazyLock<MorphSequence> = LazyLock::new(|| {
22 MorphSequence::new(
23 &[
24 shapes::soft_burst(),
25 shapes::cookie9(),
26 shapes::pentagon(),
27 shapes::pill(),
28 shapes::sunny(),
29 shapes::cookie4(),
30 shapes::oval(),
31 ],
32 true,
33 MorphPolicy::Material,
34 )
35});
36
37static DETERMINATE_SHAPES: LazyLock<MorphSequence> = LazyLock::new(|| {
38 let (sin, cos) = (TAU / 20.).sin_cos();
39 let circle = RoundedPolygon::circle()
40 .with_vertices(10)
41 .build()
42 .transformed(|p: PolygonPoint| {
43 PolygonPoint::new(p.x * cos - p.y * sin, p.x * sin + p.y * cos)
44 });
45 MorphSequence::new(
46 &[circle, shapes::soft_burst()],
47 false,
48 MorphPolicy::Material,
49 )
50});
51
52#[derive(Clone)]
54pub struct LoadingIndicatorShape(RoundedPolygon);
55
56impl LoadingIndicatorShape {
57 pub fn circle() -> Self {
58 Self(shapes::circle(None))
59 }
60
61 pub fn rounded_polygon(vertices: &[Point<f32>], radius: f32) -> Option<Self> {
64 if vertices.len() < 3 || !radius.is_finite() || radius < 0. {
65 return None;
66 }
67 let (mut vertices, side) = normalized_vertices(vertices)?;
68 if !simple_polygon(&vertices) {
69 return None;
70 }
71 let area: f32 = polygon_edges(&vertices)
72 .map(|(a, b)| a.x * b.y - a.y * b.x)
73 .sum();
74 if !area.is_finite() || area.abs() < 1e-5 {
75 return None;
76 }
77 if area < 0. {
78 vertices.reverse();
79 }
80 let first = vertices
81 .iter()
82 .enumerate()
83 .max_by(|(_, a), (_, b)| a.x.total_cmp(&b.x).then_with(|| b.y.total_cmp(&a.y)))?
84 .0;
85 vertices.rotate_left(first);
86 let rounding = CornerRounding::new((f64::from(radius) / side).min(1.) as f32);
87 let polygon = RoundedPolygon::from_vertices(&vertices, rounding, &[], PolygonPoint::zero());
88 (polygon.cubics.len() > 1).then_some(Self(polygon))
89 }
90}
91
92#[derive(Clone)]
94pub struct LoadingIndicatorShapes(Rc<MorphSequence>);
95
96impl LoadingIndicatorShapes {
97 pub fn new(shapes: impl IntoIterator<Item = LoadingIndicatorShape>) -> Option<Self> {
99 let polygons: Vec<_> = shapes.into_iter().map(|shape| shape.0).collect();
100 if polygons.len() < 2 {
101 return None;
102 }
103 Some(Self(Rc::new(MorphSequence::new(
104 &polygons,
105 true,
106 MorphPolicy::Custom,
107 ))))
108 }
109}
110
111#[derive(IntoElement)]
114pub struct LoadingIndicator {
115 id: ElementId,
116 label: SharedString,
117 contained: bool,
118 active: bool,
119 value: Option<f32>,
120 shapes: Option<LoadingIndicatorShapes>,
121 indicator_color: Option<Hsla>,
122 container_color: Option<Hsla>,
123 container_shape: CornerShape,
124}
125
126impl LoadingIndicator {
127 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
128 Self {
129 id: id.into(),
130 label: label.into(),
131 contained: false,
132 active: true,
133 value: None,
134 shapes: None,
135 indicator_color: None,
136 container_color: None,
137 container_shape: CornerShape::Full,
138 }
139 }
140
141 pub fn contained(mut self, contained: bool) -> Self {
142 self.contained = contained;
143 self
144 }
145
146 pub fn active(mut self, active: bool) -> Self {
148 self.active = active;
149 self
150 }
151
152 pub fn value(mut self, value: f32) -> Self {
154 self.value = Some(if value.is_nan() {
155 0.
156 } else {
157 value.clamp(0., 1.)
158 });
159 self
160 }
161
162 pub fn shapes(mut self, shapes: &LoadingIndicatorShapes) -> Self {
164 self.shapes = Some(shapes.clone());
165 self
166 }
167
168 pub fn indicator_color(mut self, color: impl Into<Hsla>) -> Self {
170 self.indicator_color = Some(color.into());
171 self
172 }
173
174 pub fn container_color(mut self, color: impl Into<Hsla>) -> Self {
176 self.container_color = Some(color.into());
177 self
178 }
179
180 pub fn container_shape(mut self, shape: CornerShape) -> Self {
182 self.container_shape = shape;
183 self
184 }
185}
186
187impl RenderOnce for LoadingIndicator {
188 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
189 let container_size = px(CONTAINER_SIZE);
190 if !self.active {
191 return div()
192 .id(self.id)
193 .size(container_size)
194 .flex_none()
195 .into_any_element();
196 }
197
198 let theme = window_material_theme(window, cx);
199 let fill = self.indicator_color.unwrap_or_else(|| {
200 color(theme.colors.color(if self.contained {
201 ColorRole::OnPrimaryContainer
202 } else {
203 ColorRole::Primary
204 }))
205 });
206 let background = self
207 .container_color
208 .unwrap_or_else(|| color(theme.colors.color(ColorRole::PrimaryContainer)));
209 let radii =
210 self.container_shape
211 .radii(CONTAINER_SIZE, CONTAINER_SIZE, theme.layout.direction);
212 let active_size = if self.contained {
213 let radius = radii.into_iter().fold(CONTAINER_SIZE * 0.5, f32::max);
216 ACTIVE_SIZE.min(2. * (radius - (radius - CONTAINER_SIZE * 0.5) * 2_f32.sqrt()))
217 } else {
218 ACTIVE_SIZE
219 };
220 let reduced = cx.reduce_motion();
221 let running = self.value.is_none() && !reduced && window.is_window_active();
222 let phase = if self.value.is_none() {
223 let now = cx.background_executor().now();
224 window
225 .use_keyed_state((self.id.clone(), "loading-motion"), cx, |_, _| {
226 IndeterminateMotion::default()
227 })
228 .update(cx, |state, _| state.phase(now, running, reduced))
229 } else {
230 0.
231 };
232 let icon = canvas(
233 |_, _, _| (),
234 move |bounds, _, window, _| {
235 let shapes = self.shapes.as_ref().map_or_else(
236 || {
237 if self.value.is_some() {
238 &*DETERMINATE_SHAPES
239 } else {
240 &*INDETERMINATE_SHAPES
241 }
242 },
243 |shapes| &*shapes.0,
244 );
245 let sample = match self.value {
246 Some(value) => shapes.determinate(value),
247 None => shapes.indeterminate(phase),
248 };
249 if let Some(path) = sample.path(bounds, active_size, shapes) {
250 window.paint_path(path, fill);
251 }
252 if running {
253 window.request_animation_frame();
254 }
255 },
256 )
257 .size_full();
258 let mut control = progress_node(self.id, self.label, self.value)
259 .size(container_size)
260 .flex_none()
261 .child(icon);
262 if self.contained {
263 let [tl, tr, br, bl] = radii.map(px);
264 control = control
265 .rounded_tl(tl)
266 .rounded_tr(tr)
267 .rounded_br(br)
268 .rounded_bl(bl)
269 .bg(background);
270 }
271 control.into_any_element()
272 }
273}
274
275fn progress_node(id: ElementId, label: SharedString, value: Option<f32>) -> gpui_base::Progress {
276 let control = gpui_base::Progress::new(id).accessibility_label(label);
277 match value {
278 Some(value) => control.value(value * 100.),
279 None => control.indeterminate(true).a11y_synthetic_children(|node| {
280 node.parent_node().set_live(gpui::accesskit::Live::Polite);
281 node.parent_node().set_live_atomic();
282 }),
283 }
284}
285
286#[derive(Default)]
287struct IndeterminateMotion {
288 epoch: Option<Instant>,
289 elapsed: Duration,
290}
291
292impl IndeterminateMotion {
293 fn phase(&mut self, now: Instant, running: bool, reduced: bool) -> f32 {
294 if reduced {
295 *self = Self::default();
296 return 0.;
297 }
298 let elapsed = if running {
299 self.elapsed + now.saturating_duration_since(*self.epoch.get_or_insert(now))
300 } else {
301 if let Some(epoch) = self.epoch.take() {
302 self.elapsed += now.saturating_duration_since(epoch);
303 }
304 self.elapsed
305 };
306 elapsed.as_secs_f32() / MORPH_INTERVAL
307 }
308}
309
310struct MorphSequence {
311 steps: Vec<MorphStep>,
312 wrap: Option<MorphStep>,
313 scale: f32,
314 custom_radius: Option<f32>,
315}
316
317enum MorphPolicy {
318 Material,
319 Custom,
320}
321
322impl MorphSequence {
323 fn new(shapes: &[RoundedPolygon], looping: bool, policy: MorphPolicy) -> Self {
324 let normalized: Vec<_> = shapes
325 .iter()
326 .cloned()
327 .map(RoundedPolygon::normalized)
328 .collect();
329 let step = match policy {
330 MorphPolicy::Material => MorphStep::material,
331 MorphPolicy::Custom => MorphStep::custom,
332 };
333 let custom_radius = matches!(policy, MorphPolicy::Custom).then(|| {
337 normalized
338 .iter()
339 .flat_map(|polygon| &polygon.cubics)
340 .flat_map(|cubic| {
341 [
342 cubic.anchor0(),
343 cubic.control0(),
344 cubic.control1(),
345 cubic.anchor1(),
346 ]
347 })
348 .map(|point| (point - PolygonPoint::splat(0.5)).length())
349 .fold(0_f32, f32::max)
350 });
351 Self {
352 steps: normalized
353 .windows(2)
354 .map(|pair| step(&pair[0], &pair[1]))
355 .collect(),
356 wrap: looping.then(|| step(&normalized[normalized.len() - 1], &normalized[0])),
357 scale: loading_scale(shapes),
358 custom_radius,
359 }
360 }
361
362 fn determinate(&self, value: f32) -> MorphSample<'_> {
363 let phase = value * self.steps.len() as f32;
364 let index = (phase as usize).min(self.steps.len() - 1);
365 MorphSample {
366 morph: &self.steps[index],
367 progress: phase - index as f32,
368 angle: -value * TAU * 0.5,
369 }
370 }
371
372 fn indeterminate(&self, phase: f32) -> MorphSample<'_> {
373 let count = self.steps.len() + 1;
374 let step = phase.floor();
375 let index = step as usize % count;
376 let time = phase.fract() * MORPH_INTERVAL;
377 let frequency = 200_f32.sqrt();
378 let damped = frequency * 0.8 * time;
379 let progress = (1.
380 - (-0.6 * frequency * time).exp() * (damped.cos() + 0.75 * damped.sin()))
381 .clamp(0., 1.);
382 MorphSample {
383 morph: self.steps.get(index).unwrap_or_else(|| {
384 self.wrap
385 .as_ref()
386 .expect("indeterminate morph sequences wrap")
387 }),
388 progress,
389 angle: (phase * MORPH_INTERVAL / 4.666 + (1. + step + progress) / 4.) * TAU,
390 }
391 }
392}
393
394struct MorphSample<'a> {
395 morph: &'a MorphStep,
396 progress: f32,
397 angle: f32,
398}
399
400impl MorphSample<'_> {
401 fn path(
402 self,
403 bounds: Bounds<Pixels>,
404 extent: f32,
405 sequence: &MorphSequence,
406 ) -> Option<Path<Pixels>> {
407 let cubics = self.morph.as_cubics(self.progress);
408 let first = cubics.first()?;
409 let center = cubic_center(&cubics);
410 let extent = bounds.size.width.min(bounds.size.height).min(px(extent));
411 let scaled = extent * sequence.scale;
412 let side = if let Some(radius) = sequence.custom_radius {
413 let radius = radius + (center - PolygonPoint::splat(0.5)).length();
414 scaled.min(extent / (2. * radius))
415 } else {
416 scaled
417 };
418 let (sin, cos) = self.angle.sin_cos();
419 let project = |p: PolygonPoint| {
420 let x = p.x - center.x;
421 let y = p.y - center.y;
422 bounds.center() + point(side * (cos * x - sin * y), side * (sin * x + cos * y))
423 };
424 let mut path = PathBuilder::fill();
425 path.move_to(project(first.anchor0()));
426 for cubic in cubics {
427 path.cubic_bezier_to(
428 project(cubic.anchor1()),
429 project(cubic.control0()),
430 project(cubic.control1()),
431 );
432 }
433 path.close();
434 path.build().ok()
435 }
436}
437
438enum MorphStep {
439 Material(Morph),
440 Custom(Vec<(Cubic, Cubic)>),
441}
442
443impl MorphStep {
444 fn material(start: &RoundedPolygon, end: &RoundedPolygon) -> Self {
445 Self::Material(Morph::new(start.clone(), end.clone()))
446 }
447
448 fn custom(start: &RoundedPolygon, end: &RoundedPolygon) -> Self {
449 let mut starts = weighted_segments(&start.cubics).into_iter();
453 let mut ends = weighted_segments(&end.cubics).into_iter();
454 let (mut from, mut to) = (starts.next(), ends.next());
455 let mut position = 0.;
456 let mut pairs = Vec::new();
457 while let (Some(mut a), Some(mut b)) = (from, to) {
458 let boundary = a.0.min(b.0);
459 let first = split_until(&mut a, position, boundary);
460 let last = split_until(&mut b, position, boundary);
461 pairs.push((first, last));
462 from = if boundary == a.0 {
463 starts.next()
464 } else {
465 Some(a)
466 };
467 to = if boundary == b.0 {
468 ends.next()
469 } else {
470 Some(b)
471 };
472 position = boundary;
473 }
474 Self::Custom(pairs)
475 }
476
477 fn as_cubics(&self, progress: f32) -> Vec<Cubic> {
478 match self {
479 Self::Material(morph) => morph.as_cubics(progress),
480 Self::Custom(pairs) => pairs
481 .iter()
482 .map(|(a, b)| {
483 Cubic::new(
484 a.anchor0().lerp(b.anchor0(), progress),
485 a.control0().lerp(b.control0(), progress),
486 a.control1().lerp(b.control1(), progress),
487 a.anchor1().lerp(b.anchor1(), progress),
488 )
489 })
490 .collect(),
491 }
492 }
493}
494
495fn weighted_segments(cubics: &[Cubic]) -> Vec<(f64, Cubic)> {
496 let mut cumulative = 0.;
497 let mut segments: Vec<_> = cubics
498 .iter()
499 .map(|cubic| {
500 let samples = [
501 cubic.anchor0(),
502 cubic.point_on_curve(0.25),
503 cubic.point_on_curve(0.5),
504 cubic.point_on_curve(0.75),
505 cubic.anchor1(),
506 ];
507 cumulative += samples
508 .windows(2)
509 .map(|points| f64::from((points[1] - points[0]).length()))
510 .sum::<f64>();
511 (cumulative, *cubic)
512 })
513 .collect();
514 for (end, _) in &mut segments {
515 *end /= cumulative;
516 }
517 segments
518}
519
520fn split_until(segment: &mut (f64, Cubic), from: f64, until: f64) -> Cubic {
521 if until == segment.0 {
522 return segment.1;
523 }
524 let (head, tail) = segment
525 .1
526 .split(((until - from) / (segment.0 - from)) as f32);
527 segment.1 = tail;
528 head
529}
530
531fn normalized_vertices(vertices: &[Point<f32>]) -> Option<(Vec<PolygonPoint>, f64)> {
532 let (mut left, mut top, mut right, mut bottom) = (
533 f64::INFINITY,
534 f64::INFINITY,
535 f64::NEG_INFINITY,
536 f64::NEG_INFINITY,
537 );
538 for point in vertices {
539 if !point.x.is_finite() || !point.y.is_finite() {
540 return None;
541 }
542 let x = f64::from(point.x);
543 let y = f64::from(point.y);
544 left = left.min(x);
545 top = top.min(y);
546 right = right.max(x);
547 bottom = bottom.max(y);
548 }
549 let side = (right - left).max(bottom - top);
550 if side == 0. {
551 return None;
552 }
553 let centered = vertices.iter().map(|point| {
554 PolygonPoint::new(
555 ((f64::from(point.x) - (left + right) * 0.5) / side) as f32,
556 ((f64::from(point.y) - (top + bottom) * 0.5) / side) as f32,
557 )
558 });
559 Some((centered.collect(), side))
560}
561
562fn polygon_edges(
563 vertices: &[PolygonPoint],
564) -> impl Iterator<Item = (PolygonPoint, PolygonPoint)> + Clone + '_ {
565 vertices
566 .iter()
567 .copied()
568 .zip(vertices.iter().copied().cycle().skip(1))
569}
570
571fn simple_polygon(vertices: &[PolygonPoint]) -> bool {
572 let edges = polygon_edges(vertices);
573 for (index, (a, b)) in edges.clone().enumerate() {
574 if (b - a).length() < 1e-5 {
575 return false;
576 }
577 for (other, (c, d)) in edges.clone().enumerate().skip(index + 2) {
578 if index == 0 && other == vertices.len() - 1 {
579 continue;
580 }
581 let orient = |a: PolygonPoint, b: PolygonPoint, c: PolygonPoint| {
582 let u = b - a;
583 let v = c - a;
584 u.x * v.y - u.y * v.x
585 };
586 let overlaps =
587 |a: f32, b: f32, c: f32, d: f32| a.min(b) <= c.max(d) && c.min(d) <= a.max(b);
588 if overlaps(a.x, b.x, c.x, d.x)
589 && overlaps(a.y, b.y, c.y, d.y)
590 && orient(a, b, c) * orient(a, b, d) <= 0.
591 && orient(c, d, a) * orient(c, d, b) <= 0.
592 {
593 return false;
594 }
595 }
596 }
597 true
598}
599
600fn loading_scale(shapes: &[RoundedPolygon]) -> f32 {
603 shapes.iter().fold(1., |scale, shape| {
604 let bounds = shape.aabb(true).size();
605 let radius = shape
606 .cubics
607 .iter()
608 .flat_map(|cubic| [cubic.anchor0(), cubic.point_on_curve(0.5)])
609 .map(|point| (point - shape.center).length())
610 .fold(0_f32, f32::max);
611 scale.min(bounds.width.max(bounds.height) / (2. * radius))
612 })
613}
614
615fn cubic_center(cubics: &[Cubic]) -> PolygonPoint {
616 let mut minimum = PolygonPoint::new(f32::INFINITY, f32::INFINITY);
617 let mut maximum = PolygonPoint::new(f32::NEG_INFINITY, f32::NEG_INFINITY);
618 for cubic in cubics {
619 let bounds = cubic.aabb(true);
620 minimum = minimum.min(bounds.min);
621 maximum = maximum.max(bounds.max);
622 }
623 minimum + (maximum - minimum) * 0.5
624}
625
626#[cfg(test)]
627mod tests {
628 use super::*;
629 use gpui::size;
630
631 #[test]
632 fn loading_shapes_fit_the_active_size_through_rotation_and_morphs() {
633 let shape_sets = [&*INDETERMINATE_SHAPES, &*DETERMINATE_SHAPES];
634 for shapes in shape_sets {
635 assert!(shapes.scale > 0. && shapes.scale <= 1.);
636 for morph in shapes.steps.iter().chain(shapes.wrap.iter()) {
637 for step in 0..=20 {
638 let cubics = morph.as_cubics(step as f32 / 20.);
639 let center = cubic_center(&cubics);
640 for cubic in cubics {
641 for sample in 0..=20 {
642 let p = cubic.point_on_curve(sample as f32 / 20.);
643 let radius = (p - center).length() * shapes.scale;
644 assert!(
645 radius <= 0.501,
646 "shape escapes its active envelope: {radius}"
647 );
648 }
649 }
650 }
651 }
652 }
653 }
654
655 #[test]
656 fn determinate_progress_handles_numeric_boundaries() {
657 for (input, expected) in [
658 (f32::NAN, 0.),
659 (f32::NEG_INFINITY, 0.),
660 (-0.1, 0.),
661 (0.5, 0.5),
662 (1.1, 1.),
663 (f32::INFINITY, 1.),
664 ] {
665 assert_eq!(
666 LoadingIndicator::new("loading", "Loading")
667 .value(input)
668 .value,
669 Some(expected)
670 );
671 }
672 let shapes = &*DETERMINATE_SHAPES;
673 let bounds = Bounds::new(point(px(0.), px(0.)), size(px(48.), px(48.)));
674 let start = shapes.determinate(0.);
675 let end = shapes.determinate(1.);
676 assert_eq!((start.progress, start.angle), (0., 0.));
677 assert_eq!((end.progress, end.angle), (1., -TAU * 0.5));
678 let start_path = start.path(bounds, ACTIVE_SIZE, shapes).unwrap();
679 let end_path = end.path(bounds, ACTIVE_SIZE, shapes).unwrap();
680 assert_ne!(start_path.vertices.len(), end_path.vertices.len());
681 }
682
683 #[test]
684 fn a_custom_sequence_morphs_between_endpoints_and_wraps_only_when_indeterminate() {
685 let rectangle = |w, h| {
686 LoadingIndicatorShape::rounded_polygon(
687 &[point(0., 0.), point(w, 0.), point(w, h), point(0., h)],
688 0.,
689 )
690 .unwrap()
691 };
692 let custom = LoadingIndicatorShapes::new([
693 rectangle(2., 1.),
694 LoadingIndicatorShape::circle(),
695 rectangle(1., 2.),
696 ])
697 .unwrap();
698 let shapes = &custom.0;
699 let bounds = Bounds::new(point(px(0.), px(0.)), size(px(48.), px(48.)));
700 let frame = |value| {
701 shapes
702 .determinate(value)
703 .path(bounds, ACTIVE_SIZE, shapes)
704 .unwrap()
705 .bounds
706 .size
707 };
708 let start = frame(0.);
709 let middle = frame(0.5);
710 let end = frame(1.);
711 assert!((start.width / start.height - 2.).abs() < 0.05);
712 assert!((middle.width / middle.height - 1.).abs() < 0.05);
713 assert!((end.height / end.width - 2.).abs() < 0.05);
714 for value in [0.4999, 0.5001] {
715 let adjacent = frame(value);
716 assert!((adjacent.width - middle.width).abs() < px(0.05));
717 assert!((adjacent.height - middle.height).abs() < px(0.05));
718 }
719 let first = shapes.indeterminate(0.);
720 let wrap = shapes.indeterminate(2.);
721 let repeated = shapes.indeterminate(3.);
722 assert!(std::ptr::eq(first.morph, repeated.morph));
723 assert!(std::ptr::eq(wrap.morph, shapes.wrap.as_ref().unwrap()));
724 assert_eq!(
725 (first.progress, wrap.progress, repeated.progress),
726 (0., 0., 0.)
727 );
728 }
729
730 #[test]
731 fn custom_concave_paths_align_winding_and_fit_the_active_envelope() {
732 let mut vertices = [
733 point(-1., -1.),
734 point(1., -1.),
735 point(0., 0.),
736 point(1., 1.),
737 point(-1., 1.),
738 ];
739 let polygon = LoadingIndicatorShape::rounded_polygon(&vertices, 0.1).unwrap();
740 vertices.reverse();
741 let reversed = LoadingIndicatorShape::rounded_polygon(&vertices, 0.1).unwrap();
742 assert_eq!(polygon.0.cubics, reversed.0.cubics);
743 let circle = LoadingIndicatorShape::circle();
744 let limit = polygon.0.cubics.len() + circle.0.cubics.len();
745 let sequence = LoadingIndicatorShapes::new([polygon, circle]).unwrap();
746 let shapes = &sequence.0;
747 let bounds = Bounds::new(point(px(0.), px(0.)), size(px(48.), px(48.)));
748 for step in 0..=20 {
749 let sample = shapes.determinate(step as f32 / 20.);
750 let outline = sample.morph.as_cubics(sample.progress);
751 assert!(outline.len() < limit);
752 for (a, b) in outline.iter().zip(outline.iter().cycle().skip(1)) {
753 assert!((a.anchor1() - b.anchor0()).length() < 1e-5);
754 }
755 let path = sample.path(bounds, ACTIVE_SIZE, shapes).unwrap();
756 assert!(path.vertices.iter().all(|point| {
757 let delta = point.xy_position - bounds.center();
758 f32::from(delta.x).hypot(delta.y.into()) <= ACTIVE_SIZE * 0.5 + 0.05
759 }));
760 }
761 }
762
763 #[test]
764 fn rejects_short_and_degenerate_shape_sequences() {
765 assert!(LoadingIndicatorShapes::new([]).is_none());
766 assert!(LoadingIndicatorShapes::new([LoadingIndicatorShape::circle()]).is_none());
767 for outline in [
768 &[point(0., 0.), point(0., 0.), point(0., 0.)][..],
769 &[point(0., 0.), point(1., 1.), point(2., 2.)],
770 &[point(0., 0.), point(1., 1.), point(1., 0.), point(0., 1.)],
771 &[point(0., 0.), point(f32::INFINITY, 0.), point(2., 2.)],
772 ] {
773 assert!(LoadingIndicatorShape::rounded_polygon(outline, 0.).is_none());
774 }
775 for radius in [f32::NAN, -1.] {
776 assert!(
777 LoadingIndicatorShape::rounded_polygon(
778 &[point(0., 0.), point(1., 0.), point(1., 1.)],
779 radius,
780 )
781 .is_none()
782 );
783 }
784 }
785
786 #[test]
787 fn indeterminate_phase_pauses_and_reduced_motion_holds_the_start() {
788 let mut motion = IndeterminateMotion::default();
789 let start = Instant::now();
790 let after = |millis| start + Duration::from_millis(millis);
791 assert_eq!(motion.phase(start, true, false), 0.);
792 let paused = motion.phase(after(200), false, false);
793 assert!(paused > 0.);
794 assert_eq!(motion.phase(after(400), false, false), paused);
795 assert_eq!(motion.phase(after(550), true, false), paused);
796 assert!(motion.phase(after(700), true, false) > paused);
797 assert_eq!(motion.phase(after(800), false, true), 0.);
798 assert_eq!(motion.phase(after(950), false, true), 0.);
799 assert_eq!(motion.phase(after(1050), true, false), 0.);
800 }
801}