cranpose-liquid 0.1.159

Liquid UI — cranpose's first-party glass component library (iOS-26-style materials, spring motion)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! Liquid motion: the spring presets every component shares, and the press
//! interaction (scale + specular boost) that makes glass feel physical.

use std::{
    cell::{Cell, RefCell},
    rc::Rc,
};

use cranpose_animation::{Animatable, AnimationType, Easing, spring, tween};
use cranpose_core::{RuntimeHandle, State, with_current_composer};
use cranpose_foundation::VelocityTracker1D;
use cranpose_macros::composable;
use cranpose_ui::{Modifier, MutableInteractionSource};
use cranpose_ui_graphics::GraphicsLayer;

use crate::dynamics::{LiquidDynamics, LiquidPose};

const FLUID_RELAX_MS: u64 = 420;
const VISUAL_HANDOFF_TOLERANCE_IN_ITEMS: f32 = 0.12;

pub(crate) fn liquid_visual_index(
    selected: usize,
    lens_position: f32,
    item_width: f32,
    count: usize,
    lens_owns_selection: bool,
) -> usize {
    if count == 0 {
        return 0;
    }
    let selected = selected.min(count - 1);
    if !lens_owns_selection || !lens_position.is_finite() || item_width <= f32::EPSILON {
        return selected;
    }
    ((lens_position + item_width * 0.5) / item_width)
        .floor()
        .clamp(0.0, count.saturating_sub(1) as f32) as usize
}

pub(crate) fn liquid_axis_owns_visual_selection(
    direct: bool,
    lens_position: f32,
    state_position: f32,
    item_width: f32,
) -> bool {
    direct
        || (lens_position - state_position).abs()
            > item_width.max(f32::EPSILON) * VISUAL_HANDOFF_TOLERANCE_IN_ITEMS
}

/// Named springs used across the Liquid components (value-space, velocity
/// preserving).
pub struct LiquidMotion;

impl LiquidMotion {
    /// Snappy interactions: presses, toggles, selection moves.
    pub fn snappy() -> AnimationType {
        spring(0.85, 900.0)
    }

    /// The droplet feel: visible overshoot for morphing shapes.
    pub fn bouncy() -> AnimationType {
        spring(0.55, 500.0)
    }

    /// Gentle settle for large surfaces (sheets, menus).
    pub fn smooth() -> AnimationType {
        spring(1.0, 400.0)
    }

    /// The leading edge of a stretching selection blob (runs ahead).
    pub fn blob_leading() -> AnimationType {
        spring(0.8, 900.0)
    }

    /// The trailing edge of a stretching selection blob (drags behind, giving
    /// the droplet elongation while in motion).
    pub fn blob_trailing() -> AnimationType {
        spring(0.9, 380.0)
    }

    /// A released lens flying to its committed slot: the reference
    /// bottom-bar transfer arrives in ~170 ms (on-white-click sheet,
    /// f_0040 departure to f_0050 arrival at 60 fps) with no visible
    /// overshoot; the optical settle continues after the geometry lands.
    pub fn glide() -> AnimationType {
        spring(1.0, 500.0)
    }
}

pub(crate) struct LiquidDragAxis {
    animation: RefCell<Animatable<f32>>,
    follow: Option<AnimationType>,
    pointer: Cell<Option<f32>>,
    velocity: RefCell<VelocityTracker1D>,
    runtime: RuntimeHandle,
    last_sample_ms: Cell<Option<i64>>,
    dynamics: LiquidDynamics,
    fluid_clock: RefCell<Animatable<f32>>,
}

impl LiquidDragAxis {
    fn new(initial: f32, runtime: RuntimeHandle, follow: Option<AnimationType>) -> Self {
        Self {
            follow,
            animation: RefCell::new(Animatable::new(initial, runtime.clone())),
            pointer: Cell::new(None),
            velocity: RefCell::new(VelocityTracker1D::new()),
            dynamics: LiquidDynamics::new(runtime.clone()),
            fluid_clock: RefCell::new(Animatable::new(1.0, runtime.clone())),
            runtime,
            last_sample_ms: Cell::new(None),
        }
    }

    fn arm_fluid_frames(&self) {
        let mut clock = self.fluid_clock.borrow_mut();
        clock.snapTo(0.0);
        clock.animateTo(1.0, tween(FLUID_RELAX_MS, Easing::LinearEasing));
    }

    fn sample_time_ms(&self, event_time_ms: Option<i64>) -> i64 {
        let candidate = event_time_ms
            .or_else(|| {
                self.runtime
                    .last_frame_time_nanos()
                    .map(|nanos| (nanos / 1_000_000) as i64)
            })
            .unwrap_or_else(|| self.last_sample_ms.get().unwrap_or(0) + 16);
        let monotonic = self
            .last_sample_ms
            .get()
            .map_or(candidate, |last| candidate.max(last + 1));
        self.last_sample_ms.set(Some(monotonic));
        monotonic
    }

    pub(crate) fn begin(&self, position: f32, event_time_ms: Option<i64>) {
        let time_ms = self.sample_time_ms(event_time_ms);
        let mut velocity = self.velocity.borrow_mut();
        velocity.reset();
        velocity.add_data_point(time_ms, position);
        self.pointer.set(Some(position));
        self.animation.borrow_mut().snapTo(position);
        self.dynamics.anchor_pointer((position, 0.0));
        self.arm_fluid_frames();
    }

    pub(crate) fn move_to(&self, position: f32, event_time_ms: Option<i64>) {
        self.move_to_at(
            position,
            event_time_ms,
            self.runtime.last_frame_time_nanos(),
        );
    }

    fn move_to_at(
        &self,
        position: f32,
        event_time_ms: Option<i64>,
        animation_time_nanos: Option<u64>,
    ) {
        if self.pointer.get().is_none() {
            return;
        }
        let previous_time_ms = self.last_sample_ms.get();
        let time_ms = self.sample_time_ms(event_time_ms);
        self.velocity.borrow_mut().add_data_point(time_ms, position);
        self.pointer.set(Some(position));
        if let Some(animation) = self.follow {
            let mut value = self.animation.borrow_mut();
            if let Some(time) = animation_time_nanos {
                value.animate_to_at(position, animation, time);
            } else {
                value.animateTo(position, animation);
            }
        } else {
            self.animation.borrow_mut().snapTo(position);
        }
        if let Some(previous_time_ms) = previous_time_ms.filter(|_| self.follow.is_none()) {
            let dt = (time_ms - previous_time_ms).max(1) as f32 / 1000.0;
            self.dynamics.advance_pointer((position, 0.0), dt);
        }
        self.arm_fluid_frames();
    }

    pub(crate) fn release_to(
        &self,
        target: f32,
        event_time_ms: Option<i64>,
        animation: AnimationType,
    ) {
        self.release_to_at(
            target,
            event_time_ms,
            animation,
            self.runtime.last_frame_time_nanos(),
        );
    }

    fn release_to_at(
        &self,
        target: f32,
        event_time_ms: Option<i64>,
        animation: AnimationType,
        animation_time_nanos: Option<u64>,
    ) {
        let Some(position) = self.pointer.take() else {
            self.settle_to_at(target, animation, animation_time_nanos);
            return;
        };
        let time_ms = self.sample_time_ms(event_time_ms);
        self.velocity.borrow_mut().add_data_point(time_ms, position);
        let release_velocity = if self.follow.is_some() {
            self.animation.borrow().velocity()
        } else {
            self.velocity.borrow().calculate_velocity_with_max(8_000.0)
        };
        self.dynamics.release_pointer();
        let mut value = self.animation.borrow_mut();
        if let Some(time) = animation_time_nanos {
            if self.follow.is_some() {
                value.animate_to_at(target, animation, time);
            } else {
                value.animate_to_with_velocity_at(target, release_velocity, animation, time);
            }
        } else {
            value.animate_to_with_velocity(target, release_velocity, animation);
        }
    }

    pub(crate) fn finish_at(&self, position: f32, event_time_ms: Option<i64>) {
        let Some(_) = self.pointer.get() else {
            self.animation.borrow_mut().snapTo(position);
            return;
        };
        let previous_time_ms = self.last_sample_ms.get();
        let time_ms = self.sample_time_ms(event_time_ms);
        self.velocity.borrow_mut().add_data_point(time_ms, position);
        if let Some(previous_time_ms) = previous_time_ms {
            let dt = (time_ms - previous_time_ms).max(1) as f32 / 1000.0;
            self.dynamics.advance_pointer((position, 0.0), dt);
        }
        self.pointer.set(None);
        self.animation.borrow_mut().snapTo(position);
        self.dynamics.release_pointer();
        self.arm_fluid_frames();
    }

    pub(crate) fn settle_to(&self, target: f32, animation: AnimationType) {
        self.settle_to_at(target, animation, self.runtime.last_frame_time_nanos());
    }

    fn settle_to_at(&self, target: f32, animation: AnimationType, time: Option<u64>) {
        if self.pointer.get().is_some() {
            return;
        }
        let mut value = self.animation.borrow_mut();
        if (value.target() - target).abs() > f32::EPSILON {
            if let Some(time) = time {
                value.animate_to_at(target, animation, time);
            } else {
                value.animateTo(target, animation);
            }
        }
    }

    pub(crate) fn value(&self) -> f32 {
        let _ = self.fluid_clock.borrow().state().value();
        if self.follow.is_some() {
            self.animation.borrow().state().value()
        } else {
            self.pointer
                .get()
                .unwrap_or_else(|| self.animation.borrow().state().value())
        }
    }

    pub(crate) fn liquid_pose(&self) -> LiquidPose {
        self.dynamics.update_pointer((self.value(), 0.0))
    }

    pub(crate) fn is_dragging(&self) -> bool {
        self.pointer.get().is_some()
    }
}

#[composable]
pub(crate) fn remember_liquid_drag_axis(initial: f32) -> Rc<LiquidDragAxis> {
    remember_liquid_axis(initial, None)
}

#[composable]
pub(crate) fn remember_liquid_follow_axis(
    initial: f32,
    animation: AnimationType,
) -> Rc<LiquidDragAxis> {
    remember_liquid_axis(initial, Some(animation))
}

#[composable]
fn remember_liquid_axis(initial: f32, follow: Option<AnimationType>) -> Rc<LiquidDragAxis> {
    with_current_composer(|composer| {
        let runtime = composer.runtime_handle();
        composer
            .remember(move || Rc::new(LiquidDragAxis::new(initial, runtime, follow)))
            .with(Rc::clone)
    })
}

pub(crate) struct LiquidLensGesture {
    pub axis: Rc<LiquidDragAxis>,
    pub cell_width: f32,
    pub cell_offset: f32,
    pub count: usize,
    pub tap_slop: f32,
    pub drag_left: Rc<dyn Fn(f32) -> f32>,
    pub rest_left: Rc<dyn Fn(usize) -> f32>,
    pub selected: usize,
    pub on_pressed: Rc<dyn Fn(bool, Option<u64>)>,
    pub on_touch: Rc<dyn Fn(f32, f32)>,
    pub on_select: Rc<dyn Fn(usize)>,
}

impl LiquidLensGesture {
    fn commit_index(&self, position: f32) -> usize {
        (((position - self.cell_offset) / self.cell_width.max(1.0)).floor() as isize)
            .clamp(0, self.count.saturating_sub(1) as isize) as usize
    }
}

pub(crate) async fn liquid_lens_gesture(
    scope: cranpose_ui::PointerInputScope,
    gesture: LiquidLensGesture,
) {
    use cranpose_foundation::{PointerEventKind, PointerId};
    use cranpose_services::{HapticFeedback, default_haptics};

    scope
        .await_pointer_event_scope(|await_scope| async move {
            let mut down_x = 0.0f32;
            let mut moved = false;
            let mut active_pointer = Option::<PointerId>::None;
            loop {
                let event = await_scope.await_pointer_event().await;
                match event.kind {
                    PointerEventKind::Down if active_pointer.is_none() => {
                        active_pointer = Some(event.id);
                        down_x = event.position.x;
                        moved = false;
                        gesture.axis.settle_to_at(
                            (gesture.rest_left)(gesture.commit_index(down_x)),
                            LiquidMotion::glide(),
                            event.animation_time_nanos,
                        );
                        (gesture.on_pressed)(true, event.animation_time_nanos);
                        (gesture.on_touch)(event.position.x, event.position.y);
                        default_haptics().perform(HapticFeedback::Selection);
                        event.consume();
                    }
                    PointerEventKind::Move if active_pointer == Some(event.id) => {
                        moved |= (event.position.x - down_x).abs() > gesture.tap_slop;
                        if moved {
                            let target = (gesture.drag_left)(event.position.x);
                            if gesture.axis.is_dragging() {
                                gesture.axis.move_to_at(
                                    target,
                                    event.time_ms,
                                    event.animation_time_nanos,
                                );
                            } else if (gesture.axis.value() - target).abs()
                                <= gesture.cell_width * 0.6
                            {
                                gesture.axis.begin(gesture.axis.value(), event.time_ms);
                                gesture.axis.move_to_at(
                                    target,
                                    event.time_ms,
                                    event.animation_time_nanos,
                                );
                            } else {
                                gesture.axis.settle_to_at(
                                    target,
                                    LiquidMotion::glide(),
                                    event.animation_time_nanos,
                                );
                            }
                        }
                        (gesture.on_touch)(event.position.x, event.position.y);
                        event.consume();
                    }
                    PointerEventKind::Up if active_pointer == Some(event.id) => {
                        active_pointer = None;
                        (gesture.on_pressed)(false, event.animation_time_nanos);
                        let commit_x = if moved { event.position.x } else { down_x };
                        let index = gesture.commit_index(commit_x);
                        gesture.axis.release_to_at(
                            (gesture.rest_left)(index),
                            event.time_ms,
                            LiquidMotion::glide(),
                            event.animation_time_nanos,
                        );
                        default_haptics().perform(HapticFeedback::ImpactLight);
                        (gesture.on_select)(index);
                        event.consume();
                    }
                    PointerEventKind::Cancel if active_pointer == Some(event.id) => {
                        active_pointer = None;
                        (gesture.on_pressed)(false, event.animation_time_nanos);
                        gesture.axis.release_to_at(
                            (gesture.rest_left)(gesture.selected),
                            event.time_ms,
                            LiquidMotion::glide(),
                            event.animation_time_nanos,
                        );
                        event.consume();
                    }
                    _ => {}
                }
            }
        })
        .await;
}

/// Press feedback for glass controls, per the Liquid Glass law: touched glass
/// GROWS (spring scale toward `pressed_scale` — never smaller) and turns MORE
/// TRANSPARENT (the returned content alpha dips while pressed, the reference
/// "…" dots fading as the button lifts). Returns the pressed state so callers
/// can also boost the specular highlight.
///
/// Apply the returned modifier *outside* the glass effect so the whole lens
/// scales together; apply the content alpha to the label/icon layer.
#[composable]
pub fn liquid_press_scale(
    modifier: Modifier,
    interaction_source: MutableInteractionSource,
    pressed_scale: f32,
) -> (Modifier, State<bool>, State<f32>) {
    let pressed = interaction_source.collectIsPressedAsState();
    let scale = cranpose_animation::animateFloatAsState(
        if pressed.get() {
            pressed_scale.max(1.0)
        } else {
            1.0
        },
        LiquidMotion::snappy(),
        "liquid-press-scale",
    );
    let content_alpha = cranpose_animation::animateFloatAsState(
        if pressed.get() { 0.35 } else { 1.0 },
        LiquidMotion::smooth(),
        "liquid-press-content",
    );
    let modifier = modifier.graphics_layer(move || {
        let scale = scale.get();
        GraphicsLayer {
            scale_x: scale,
            scale_y: scale,
            ..Default::default()
        }
    });
    (modifier, pressed, content_alpha)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn axis(initial: f32) -> (cranpose_core::Runtime, LiquidDragAxis) {
        let runtime =
            cranpose_core::Runtime::new(std::sync::Arc::new(cranpose_core::DefaultScheduler));
        let axis = LiquidDragAxis::new(initial, runtime.handle(), None);
        (runtime, axis)
    }

    fn native_trace_error(follow: Option<AnimationType>) -> f32 {
        let runtime =
            cranpose_core::Runtime::new(std::sync::Arc::new(cranpose_core::DefaultScheduler));
        let mut axis = LiquidDragAxis::new(0.0, runtime.handle(), follow);
        let mut origin = 1_000_000_000u64;
        let mut squared_error = 0.0;
        let mut count = 0;
        for line in include_str!("../tests/fixtures/native_tab_drag.csv").lines() {
            let fields: Vec<_> = line.split(',').collect();
            let time: f64 = fields[1].parse().expect("trace time");
            let position: f32 = fields[2].parse().expect("trace position");
            if fields[0] == "start" {
                origin += 10_000_000_000;
                axis = LiquidDragAxis::new(position, runtime.handle(), follow);
                runtime.handle().drain_frame_callbacks(origin);
                axis.begin(position, Some((origin / 1_000_000) as i64));
                continue;
            }
            let nanos = origin + (time * 1e9) as u64;
            runtime.handle().drain_frame_callbacks(nanos);
            if fields[0] == "input" {
                axis.move_to(position, Some((nanos / 1_000_000) as i64));
            } else {
                squared_error += (axis.value() - position).powi(2);
                count += 1;
            }
        }
        assert!(count > 200);
        (squared_error / count as f32).sqrt()
    }

    #[test]
    fn tab_follow_matches_both_native_drag_velocities_and_held_settling() {
        let following = native_trace_error(Some(spring(0.85, 650.0)));
        let direct = native_trace_error(None);
        assert!(following < 3.0, "native trace RMS: {following}");
        assert!(direct > 15.0, "direct-input counterexample RMS: {direct}");
    }

    #[test]
    fn releasing_a_following_lens_preserves_its_rendered_velocity() {
        let runtime =
            cranpose_core::Runtime::new(std::sync::Arc::new(cranpose_core::DefaultScheduler));
        let axis = LiquidDragAxis::new(0.0, runtime.handle(), Some(spring(0.85, 650.0)));
        runtime.handle().drain_frame_callbacks(1_000_000_000);
        axis.begin(0.0, Some(1000));
        axis.move_to(100.0, Some(1016));
        runtime.handle().drain_frame_callbacks(1_016_000_000);
        runtime.handle().drain_frame_callbacks(1_032_000_000);
        let before = axis.animation.borrow().velocity();
        assert!(before > 0.0);
        axis.release_to(100.0, Some(1200), LiquidMotion::glide());
        assert_eq!(axis.animation.borrow().velocity(), before);
        assert!(!axis.is_dragging());
    }

    #[test]
    fn pointer_samples_are_the_visual_coordinate_without_a_chase() {
        let (_runtime, axis) = axis(10.0);
        axis.begin(20.0, Some(0));
        assert_eq!(axis.value(), 20.0);
        axis.move_to(180.0, Some(16));
        assert_eq!(axis.value(), 180.0);
    }

    #[test]
    fn direct_manipulation_owns_visual_selection_until_the_lens_reaches_state() {
        assert_eq!(liquid_visual_index(2, 0.0, 78.0, 4, false), 2);
        assert_eq!(liquid_visual_index(0, 2.0 * 78.0, 78.0, 4, true), 2);
        assert_eq!(liquid_visual_index(0, 1.6 * 78.0, 78.0, 4, true), 2);
        assert_eq!(liquid_visual_index(0, 1.4 * 78.0, 78.0, 4, true), 1);
        assert_eq!(liquid_visual_index(0, 2.71 * 78.0, 78.0, 4, true), 3);
        assert_eq!(liquid_visual_index(0, 3.0 * 78.0, 78.0, 4, true), 3);
        assert_eq!(liquid_visual_index(0, 99.0 * 78.0, 78.0, 4, true), 3);
        assert_eq!(liquid_visual_index(9, f32::NAN, 78.0, 4, true), 3);
        assert_eq!(liquid_visual_index(0, 78.0, 0.0, 4, true), 0);

        assert!(liquid_axis_owns_visual_selection(true, 0.0, 0.0, 78.0));
        assert!(liquid_axis_owns_visual_selection(false, 78.0, 0.0, 78.0));
        assert!(!liquid_axis_owns_visual_selection(
            false,
            78.0 * 0.05,
            0.0,
            78.0,
        ));
    }

    #[test]
    fn pointer_sample_excites_the_incompressible_pose_before_render() {
        let (_runtime, axis) = axis(0.0);
        axis.begin(0.0, Some(0));
        axis.move_to(14.0, Some(16));
        let pose = axis.liquid_pose();
        let deformation = (pose.stretch - 1.0).abs();
        assert!(
            (0.08..=0.12).contains(&deformation),
            "the direct-input frame must deform visibly without treating one sample as extreme acceleration: {pose:?}"
        );
        assert!((pose.stretch * pose.ortho - 1.0).abs() < 1e-4);
        assert_eq!(axis.value(), 14.0);
    }

    #[test]
    fn render_without_a_new_pointer_sample_preserves_velocity_continuity() {
        let (_runtime, axis) = axis(0.0);
        axis.runtime.drain_frame_callbacks(1_000_000);
        axis.begin(0.0, Some(0));
        axis.move_to(14.0, Some(16));
        let sampled = axis.liquid_pose();

        axis.runtime.drain_frame_callbacks(17_000_000);
        let next_frame = axis.liquid_pose();

        assert!(
            (next_frame.stretch - sampled.stretch).abs() < 0.08,
            "a render frame without input must not synthesize a brake impulse: {sampled:?} -> {next_frame:?}"
        );
        assert!((next_frame.stretch * next_frame.ortho - 1.0).abs() < 1e-4);
    }

    #[test]
    fn controlled_retargets_wait_until_direct_manipulation_ends() {
        let (_runtime, axis) = axis(10.0);
        axis.begin(40.0, Some(0));
        axis.settle_to(90.0, LiquidMotion::snappy());
        assert_eq!(axis.value(), 40.0);
        axis.release_to(90.0, Some(16), LiquidMotion::snappy());
        assert!(!axis.is_dragging());
        assert_eq!(axis.animation.borrow().target(), 90.0);
    }

    #[test]
    fn continuous_release_stops_translation_without_erasing_fluid_velocity() {
        let (_runtime, axis) = axis(0.0);
        axis.runtime.drain_frame_callbacks(1_000_000);
        axis.begin(0.0, Some(0));
        axis.move_to(80.0, Some(16));
        let moving = axis.liquid_pose();

        axis.finish_at(80.0, Some(17));
        assert!(!axis.is_dragging());
        assert_eq!(axis.value(), 80.0);
        assert!(moving.speed > 0.0);

        let mut relaxed = moving;
        for frame in 2..=12 {
            axis.runtime.drain_frame_callbacks(frame * 17_000_000);
            assert_eq!(axis.value(), 80.0, "frame {frame} backtracked");
            relaxed = axis.liquid_pose();
        }
        assert!(
            relaxed.speed < moving.speed,
            "shape velocity must relax even though translation stops"
        );
    }

    #[test]
    fn released_flight_is_critically_damped() {
        let AnimationType::Spring(spec) = LiquidMotion::glide() else {
            panic!("released flight must use a spring");
        };
        assert_eq!(spec.damping_ratio, 1.0);
        assert_eq!(spec.stiffness, 500.0);
    }

    fn spring_of(animation: AnimationType) -> cranpose_animation::SpringSpec {
        match animation {
            AnimationType::Spring(spec) => spec,
            other => panic!("expected a spring, got {other:?}"),
        }
    }

    #[test]
    fn a_stretching_blob_runs_its_leading_edge_ahead_of_its_trailing_edge() {
        let leading = spring_of(LiquidMotion::blob_leading());
        let trailing = spring_of(LiquidMotion::blob_trailing());
        assert!(
            leading.stiffness > trailing.stiffness,
            "the edge that runs ahead has to be the stiffer one: \
             leading {} vs trailing {}",
            leading.stiffness,
            trailing.stiffness
        );
        assert!(
            leading.damping_ratio < 1.0 && trailing.damping_ratio < 1.0,
            "both edges stay under-damped so the droplet keeps its elongation"
        );
    }

    #[test]
    fn every_named_motion_is_a_settled_spring() {
        for (name, animation) in [
            ("snappy", LiquidMotion::snappy()),
            ("bouncy", LiquidMotion::bouncy()),
            ("smooth", LiquidMotion::smooth()),
            ("blob_leading", LiquidMotion::blob_leading()),
            ("blob_trailing", LiquidMotion::blob_trailing()),
            ("glide", LiquidMotion::glide()),
        ] {
            let spec = spring_of(animation);
            assert!(spec.stiffness > 0.0, "{name} needs a stiffness");
            assert!(spec.damping_ratio > 0.0, "{name} needs damping");
            assert_eq!(spec.delay_millis, 0, "{name} starts on the frame it is set");
        }
    }
}