1#![allow(non_snake_case)]
12
13use cranpose_animation::{
14 AnimationSpec, Easing, RepeatMode, StartOffset, infiniteRepeatable, rememberInfiniteTransition,
15};
16use cranpose_core::NodeId;
17use cranpose_ui_graphics::{Brush, Color, Rect, VectorPath};
18
19use crate::{composable, modifier::Modifier, widgets::Canvas};
20
21pub const CIRCULAR_INDICATOR_DIAMETER: f32 = 20.0;
23
24pub const CIRCULAR_INDICATOR_STROKE_WIDTH: f32 = 2.0;
28
29pub const PROGRESS_INDICATOR_COLOR: Color = Color(0.101, 0.462, 0.909, 1.0);
31
32pub const LINEAR_INDICATOR_WIDTH: f32 = 240.0;
34pub const LINEAR_INDICATOR_HEIGHT: f32 = 4.0;
36
37const ROTATION_DURATION_MS: u64 = 1332;
39const SWEEP_DURATION_MS: u64 = 666;
41const MIN_SWEEP_DEGREES: f32 = 30.0;
43const MAX_SWEEP_DEGREES: f32 = 270.0;
45const LINEAR_SLIDE_DURATION_MS: u64 = 1200;
47const LINEAR_BAND_FRACTION: f32 = 0.4;
49const LINEAR_TRACK_ALPHA: f32 = 0.24;
51
52#[composable]
77pub fn CircularProgressIndicator(modifier: Modifier, color: Color, stroke_width: f32) -> NodeId {
78 let transition = rememberInfiniteTransition("circular_progress_indicator");
79 let rotation = transition.animateFloat(
80 0.0,
81 360.0,
82 infiniteRepeatable(
83 AnimationSpec::linear(ROTATION_DURATION_MS),
84 RepeatMode::Restart,
85 StartOffset::default(),
86 ),
87 "circular_progress_rotation",
88 );
89 let sweep = transition.animateFloat(
90 MIN_SWEEP_DEGREES,
91 MAX_SWEEP_DEGREES,
92 infiniteRepeatable(
93 AnimationSpec::tween(SWEEP_DURATION_MS, Easing::EaseInOut),
94 RepeatMode::Reverse,
95 StartOffset::default(),
96 ),
97 "circular_progress_sweep",
98 );
99
100 let sized = modifier.size_points(CIRCULAR_INDICATOR_DIAMETER, CIRCULAR_INDICATOR_DIAMETER);
101 Canvas(sized, move |scope| {
102 let size = scope.size();
103 let start_angle = rotation.get() - 90.0;
104 let sweep_angle = sweep.get();
105 if let Some(data) = circular_arc_path_data(
106 size.width,
107 size.height,
108 stroke_width,
109 start_angle,
110 sweep_angle,
111 ) {
112 if let Ok(path) = VectorPath::parse(&data) {
113 scope.draw_vector_path(&path, Brush::solid(color));
114 }
115 }
116 })
117}
118
119#[composable]
131pub fn LinearProgressIndicator(modifier: Modifier, color: Color) -> NodeId {
132 let transition = rememberInfiniteTransition("linear_progress_indicator");
133 let phase = transition.animateFloat(
134 0.0,
135 1.0,
136 infiniteRepeatable(
137 AnimationSpec::tween(LINEAR_SLIDE_DURATION_MS, Easing::FastOutSlowInEasing),
138 RepeatMode::Restart,
139 StartOffset::default(),
140 ),
141 "linear_progress_phase",
142 );
143
144 let sized = modifier.size_points(LINEAR_INDICATOR_WIDTH, LINEAR_INDICATOR_HEIGHT);
145 Canvas(sized, move |scope| {
146 let size = scope.size();
147 let track = Color(color.0, color.1, color.2, color.3 * LINEAR_TRACK_ALPHA);
148 scope.draw_rect(Brush::solid(track));
149 if let Some((x, width)) = linear_indicator_band(size.width, phase.get()) {
150 scope.draw_rect_at(
151 Rect {
152 x,
153 y: 0.0,
154 width,
155 height: size.height,
156 },
157 Brush::solid(color),
158 );
159 }
160 })
161}
162
163pub(crate) fn circular_arc_path_data(
170 width: f32,
171 height: f32,
172 stroke_width: f32,
173 start_angle_deg: f32,
174 sweep_angle_deg: f32,
175) -> Option<String> {
176 let outer_r = width.min(height) * 0.5;
177 if outer_r <= 0.0 {
178 return None;
179 }
180 let sweep = sweep_angle_deg.clamp(0.0, 359.9);
181 if sweep <= 0.0 {
182 return None;
183 }
184 let stroke = stroke_width.clamp(0.1, outer_r);
185 let inner_r = (outer_r - stroke).max(0.0);
186 let cx = width * 0.5;
187 let cy = height * 0.5;
188 let a0 = start_angle_deg.to_radians();
189 let a1 = (start_angle_deg + sweep).to_radians();
190 let (ox0, oy0) = (cx + outer_r * a0.cos(), cy + outer_r * a0.sin());
191 let (ox1, oy1) = (cx + outer_r * a1.cos(), cy + outer_r * a1.sin());
192 let (ix0, iy0) = (cx + inner_r * a0.cos(), cy + inner_r * a0.sin());
193 let (ix1, iy1) = (cx + inner_r * a1.cos(), cy + inner_r * a1.sin());
194 let large_arc = if sweep > 180.0 { 1 } else { 0 };
195 Some(format!(
196 "M {ox0:.4} {oy0:.4} \
197 A {outer_r:.4} {outer_r:.4} 0 {large_arc} 1 {ox1:.4} {oy1:.4} \
198 L {ix1:.4} {iy1:.4} \
199 A {inner_r:.4} {inner_r:.4} 0 {large_arc} 0 {ix0:.4} {iy0:.4} Z"
200 ))
201}
202
203pub(crate) fn linear_indicator_band(width: f32, phase: f32) -> Option<(f32, f32)> {
209 if width <= 0.0 {
210 return None;
211 }
212 let band_width = width * LINEAR_BAND_FRACTION;
213 let x = phase * (width + band_width) - band_width;
214 let x0 = x.max(0.0);
215 let x1 = (x + band_width).min(width);
216 (x1 > x0).then_some((x0, x1 - x0))
217}
218
219#[cfg(test)]
220mod tests {
221 use std::sync::Arc;
222
223 use cranpose_core::{Composition, DefaultScheduler, MemoryApplier, Runtime, location_key};
224
225 use super::*;
226
227 fn with_test_runtime<T>(f: impl FnOnce() -> T) -> T {
228 let _runtime = Runtime::new(Arc::new(DefaultScheduler));
229 f()
230 }
231
232 #[test]
233 fn circular_arc_path_parses_and_stays_in_bounds() {
234 for rotation in [0.0_f32, 45.0, 90.0, 200.0, 355.0] {
235 for sweep in [MIN_SWEEP_DEGREES, 120.0, MAX_SWEEP_DEGREES] {
236 let data = circular_arc_path_data(
237 CIRCULAR_INDICATOR_DIAMETER,
238 CIRCULAR_INDICATOR_DIAMETER,
239 CIRCULAR_INDICATOR_STROKE_WIDTH,
240 rotation - 90.0,
241 sweep,
242 )
243 .expect("arc path data");
244 let path = VectorPath::parse(&data).expect("valid SVG arc path");
245 assert!(!path.is_empty(), "arc path must produce geometry");
246 let bounds = path.bounds();
247 let eps = 0.51;
248 assert!(
249 bounds.x >= -eps
250 && bounds.y >= -eps
251 && bounds.x + bounds.width <= CIRCULAR_INDICATOR_DIAMETER + eps
252 && bounds.y + bounds.height <= CIRCULAR_INDICATOR_DIAMETER + eps,
253 "arc (rotation {rotation}, sweep {sweep}) escapes indicator bounds: {bounds:?}"
254 );
255 }
256 }
257 }
258
259 #[test]
260 fn circular_arc_path_rotates_with_angle() {
261 let at = |start: f32| {
262 circular_arc_path_data(20.0, 20.0, 2.0, start, 120.0).expect("arc path data")
263 };
264 assert_ne!(at(0.0), at(90.0), "rotation must move the arc");
265 }
266
267 #[test]
268 fn circular_arc_path_rejects_degenerate_input() {
269 assert!(circular_arc_path_data(0.0, 0.0, 2.0, 0.0, 120.0).is_none());
270 assert!(circular_arc_path_data(20.0, 20.0, 2.0, 0.0, 0.0).is_none());
271 }
272
273 #[test]
274 fn linear_band_stays_inside_track() {
275 let width = 200.0;
276 let mut seen_band = false;
277 for step in 0..=20 {
278 let phase = step as f32 / 20.0;
279 if let Some((x, band_width)) = linear_indicator_band(width, phase) {
280 seen_band = true;
281 assert!(x >= 0.0, "band start below 0 at phase {phase}");
282 assert!(
283 x + band_width <= width + 1e-3,
284 "band escapes track at phase {phase}"
285 );
286 assert!(band_width > 0.0);
287 }
288 }
289 assert!(seen_band, "band must be visible for mid phases");
290 assert!(linear_indicator_band(width, 0.0).is_none());
291 assert!(linear_indicator_band(width, 1.0).is_none());
292 }
293
294 #[test]
295 fn circular_progress_indicator_composes() {
296 let _app_context = crate::render_state::app_context_test_scope();
297 with_test_runtime(|| {
298 let mut composition = Composition::new(MemoryApplier::new());
299 let result = composition.render(location_key(file!(), line!(), column!()), || {
300 CircularProgressIndicator(
301 Modifier::empty(),
302 PROGRESS_INDICATOR_COLOR,
303 CIRCULAR_INDICATOR_STROKE_WIDTH,
304 );
305 });
306 assert!(result.is_ok());
307 assert!(composition.root().is_some());
308 });
309 }
310
311 #[test]
312 fn linear_progress_indicator_composes() {
313 let _app_context = crate::render_state::app_context_test_scope();
314 with_test_runtime(|| {
315 let mut composition = Composition::new(MemoryApplier::new());
316 let result = composition.render(location_key(file!(), line!(), column!()), || {
317 LinearProgressIndicator(Modifier::empty(), PROGRESS_INDICATOR_COLOR);
318 });
319 assert!(result.is_ok());
320 assert!(composition.root().is_some());
321 });
322 }
323
324 #[test]
325 fn circular_progress_indicator_animates_transition() {
326 use crate::{layout::MeasureLayoutOptions, measure_layout_with_options};
327
328 let _app_context = crate::render_state::app_context_test_scope();
329 let mut composition = Composition::new(MemoryApplier::new());
330 composition
331 .render(location_key(file!(), line!(), column!()), || {
332 CircularProgressIndicator(
333 Modifier::empty(),
334 PROGRESS_INDICATOR_COLOR,
335 CIRCULAR_INDICATOR_STROKE_WIDTH,
336 );
337 })
338 .expect("initial render");
339
340 let root = composition.root().expect("composition root");
341 let handle = composition.runtime_handle();
342
343 fn collect_draw_commands(
344 node: &crate::LayoutBox,
345 out: &mut Vec<(crate::DrawCommand, crate::modifier::Size)>,
346 ) {
347 for command in node.node_data.modifier_slices().draw_commands() {
348 out.push((
349 command.clone(),
350 crate::modifier::Size {
351 width: node.rect.width,
352 height: node.rect.height,
353 },
354 ));
355 }
356 for child in &node.children {
357 collect_draw_commands(child, out);
358 }
359 }
360
361 let commands = {
362 let mut applier = composition.applier_mut();
363 applier.set_runtime_handle(handle.clone());
364 let measurements = measure_layout_with_options(
365 &mut applier,
366 root,
367 crate::Size::new(200.0, 200.0),
368 MeasureLayoutOptions {
369 collect_semantics: false,
370 build_layout_tree: true,
371 },
372 )
373 .expect("measure spinner layout");
374 applier.clear_runtime_handle();
375
376 let tree = measurements.layout_tree().expect("layout tree");
377 let mut commands = Vec::new();
378 collect_draw_commands(tree.root(), &mut commands);
379 commands
380 };
381 assert!(!commands.is_empty(), "spinner must register draw commands");
382
383 let run_commands = |commands: &[(crate::DrawCommand, crate::modifier::Size)]| {
384 use cranpose_ui_graphics::DrawScope as _;
385 commands
386 .iter()
387 .flat_map(|(command, size)| {
388 let func = match command {
389 crate::DrawCommand::Behind(func) => func,
390 crate::DrawCommand::Overlay(func) => func,
391 crate::DrawCommand::WithContent(func) => func,
392 };
393 let mut scope = crate::draw::command_draw_scope(*size);
394 func(&mut scope);
395 scope.into_primitives()
396 })
397 .collect::<Vec<_>>()
398 };
399
400 let before = run_commands(&commands);
401 assert!(
402 !before.is_empty(),
403 "spinner draw closure must emit primitives"
404 );
405
406 let mut time = 0u64;
407 for _ in 0..30 {
408 time += 16_666_667;
409 handle.drain_frame_callbacks(time);
410 composition
411 .process_invalid_scopes()
412 .expect("process invalid scopes");
413 }
414
415 let after = run_commands(&commands);
416 assert_ne!(
417 before, after,
418 "spinner draw primitives must change as the transition animates"
419 );
420 }
421}