open-gpui-motion 0.2.0

Renderer-neutral motion primitives for Open GPUI.
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! Renderer-neutral spring sampling for layout-like UI motion.

use crate::{MotionPreference, MotionRunState, MotionSpec, MotionTimeline};
use std::time::{Duration, Instant};

const DEFAULT_MASS: f32 = 1.0;
const DEFAULT_STIFFNESS: f32 = 260.0;
const DEFAULT_DAMPING: f32 = 28.0;
const DEFAULT_REST_DELTA: f32 = 0.001;
const DEFAULT_REST_SPEED: f32 = 0.01;
const MIN_POSITIVE: f32 = 0.000_001;
const MAX_PHYSICS_VALUE: f32 = 1_000_000.0;

/// Reviewable spring presets for layout-like UI motion.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MotionSpringPreset {
    /// Short, subtle affordance motion.
    Affordance,
    /// Committed layout motion such as collapse, expand, insert, or remove.
    Layout,
    /// Continuity motion for retargeted pane, divider, or zoom transitions.
    Continuity,
}

/// Renderer-neutral spring physics parameters.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MotionSpringPhysics {
    mass: f32,
    stiffness: f32,
    damping: f32,
    rest_delta: f32,
    rest_speed: f32,
    bounce: f32,
    review_duration: Duration,
}

impl MotionSpringPhysics {
    /// Maximum bounce value accepted by professional UI policy.
    pub const MAX_REVIEWABLE_BOUNCE: f32 = 0.35;

    /// Creates sanitized spring physics parameters.
    pub fn new(mass: f32, stiffness: f32, damping: f32) -> Self {
        Self {
            mass: sanitize_positive(mass, DEFAULT_MASS),
            stiffness: sanitize_positive(stiffness, DEFAULT_STIFFNESS),
            damping: sanitize_non_negative(damping, DEFAULT_DAMPING),
            rest_delta: DEFAULT_REST_DELTA,
            rest_speed: DEFAULT_REST_SPEED,
            bounce: 0.0,
            review_duration: Duration::from_millis(180),
        }
    }

    /// Returns the mass parameter.
    pub const fn mass(self) -> f32 {
        self.mass
    }

    /// Returns the stiffness parameter.
    pub const fn stiffness(self) -> f32 {
        self.stiffness
    }

    /// Returns the damping parameter.
    pub const fn damping(self) -> f32 {
        self.damping
    }

    /// Returns the position rest threshold.
    pub const fn rest_delta(self) -> f32 {
        self.rest_delta
    }

    /// Returns the velocity rest threshold.
    pub const fn rest_speed(self) -> f32 {
        self.rest_speed
    }

    /// Returns the review-facing bounce value.
    pub const fn bounce(self) -> f32 {
        self.bounce
    }

    /// Returns the expected review duration for policy checks.
    pub const fn review_duration(self) -> Duration {
        self.review_duration
    }

    /// Returns a copy with a sanitized position rest threshold.
    pub fn with_rest_delta(mut self, rest_delta: f32) -> Self {
        self.rest_delta = sanitize_positive(rest_delta, DEFAULT_REST_DELTA);
        self
    }

    /// Returns a copy with a sanitized velocity rest threshold.
    pub fn with_rest_speed(mut self, rest_speed: f32) -> Self {
        self.rest_speed = sanitize_positive(rest_speed, DEFAULT_REST_SPEED);
        self
    }

    /// Returns a copy with a review-facing bounce value clamped to policy range.
    pub fn with_bounce(mut self, bounce: f32) -> Self {
        self.bounce = if bounce.is_finite() {
            bounce.clamp(0.0, Self::MAX_REVIEWABLE_BOUNCE)
        } else {
            0.0
        };
        self
    }

    /// Returns a copy with the expected review duration used by policy checks.
    pub fn with_review_duration(mut self, duration: Duration) -> Self {
        self.review_duration = duration;
        self
    }
}

/// Renderer-neutral spring motion specification.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MotionSpringSpec {
    preference: MotionPreference,
    preset: Option<MotionSpringPreset>,
    physics: MotionSpringPhysics,
}

impl MotionSpringSpec {
    /// Creates a spring spec from preference and explicit physics.
    pub fn from_physics(preference: MotionPreference, physics: MotionSpringPhysics) -> Self {
        Self {
            preference,
            preset: None,
            physics,
        }
    }

    /// Creates the default affordance spring spec for the given preference.
    pub fn affordance(preference: MotionPreference) -> Self {
        Self::from_preset(
            preference,
            MotionSpringPreset::Affordance,
            MotionSpringPhysics::new(1.0, 320.0, 34.0)
                .with_bounce(0.08)
                .with_review_duration(Duration::from_millis(120)),
        )
    }

    /// Creates the default committed layout spring spec for the given preference.
    pub fn layout(preference: MotionPreference) -> Self {
        Self::from_preset(
            preference,
            MotionSpringPreset::Layout,
            MotionSpringPhysics::new(1.0, 260.0, 28.0)
                .with_bounce(0.12)
                .with_review_duration(Duration::from_millis(180)),
        )
    }

    /// Creates the default continuity spring spec for the given preference.
    pub fn continuity(preference: MotionPreference) -> Self {
        Self::from_preset(
            preference,
            MotionSpringPreset::Continuity,
            MotionSpringPhysics::new(1.0, 190.0, 23.0)
                .with_bounce(0.10)
                .with_review_duration(Duration::from_millis(260)),
        )
    }

    fn from_preset(
        preference: MotionPreference,
        preset: MotionSpringPreset,
        physics: MotionSpringPhysics,
    ) -> Self {
        Self {
            preference,
            preset: Some(preset),
            physics,
        }
    }

    /// Returns the motion preference.
    pub const fn preference(self) -> MotionPreference {
        self.preference
    }

    /// Returns the optional reviewable preset.
    pub const fn preset(self) -> Option<MotionSpringPreset> {
        self.preset
    }

    /// Returns the sanitized physics parameters.
    pub const fn physics(self) -> MotionSpringPhysics {
        self.physics
    }

    /// Returns whether this spring completes immediately.
    pub const fn is_immediate(self) -> bool {
        self.preference.is_immediate()
    }

    /// Returns a copy with review-facing bounce clamped to policy range.
    pub fn with_bounce(mut self, bounce: f32) -> Self {
        self.physics = self.physics.with_bounce(bounce);
        self
    }
}

/// Explicit preset that resolves to a concrete motion model.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MotionPreset {
    /// Immediate completion.
    Immediate,
    /// Duration/easing timeline motion.
    Timeline(MotionSpec),
    /// Explicit spring motion.
    Spring(MotionSpringSpec),
    /// Default committed layout spring.
    CommittedLayout(MotionPreference),
    /// Default continuity spring.
    Continuity(MotionPreference),
    /// Default affordance spring.
    Affordance(MotionPreference),
}

impl MotionPreset {
    /// Creates an immediate preset.
    pub const fn immediate() -> Self {
        Self::Immediate
    }

    /// Creates an explicit timeline preset.
    pub const fn timeline(spec: MotionSpec) -> Self {
        Self::Timeline(spec)
    }

    /// Creates an explicit spring preset.
    pub const fn spring(spec: MotionSpringSpec) -> Self {
        Self::Spring(spec)
    }

    /// Creates the default committed layout preset.
    pub const fn committed_layout(preference: MotionPreference) -> Self {
        Self::CommittedLayout(preference)
    }

    /// Creates the default continuity preset.
    pub const fn continuity(preference: MotionPreference) -> Self {
        Self::Continuity(preference)
    }

    /// Creates the default affordance preset.
    pub const fn affordance(preference: MotionPreference) -> Self {
        Self::Affordance(preference)
    }

    /// Resolves this preset to the concrete motion model that should execute.
    pub fn resolve_model(self) -> MotionModel {
        match self {
            Self::Immediate => MotionModel::timeline(MotionSpec::immediate()),
            Self::Timeline(spec) => MotionModel::timeline(spec),
            Self::Spring(spec) => MotionModel::spring(spec),
            Self::CommittedLayout(preference) => {
                MotionModel::spring(MotionSpringSpec::layout(preference))
            }
            Self::Continuity(preference) => {
                MotionModel::spring(MotionSpringSpec::continuity(preference))
            }
            Self::Affordance(preference) => {
                MotionModel::spring(MotionSpringSpec::affordance(preference))
            }
        }
    }
}

/// A sampled point on a scalar motion model.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MotionScalarSample {
    state: MotionRunState,
    elapsed: Duration,
    value: f32,
    velocity: f32,
    target: f32,
}

impl MotionScalarSample {
    /// Creates a scalar motion sample from explicit values.
    pub const fn new(
        state: MotionRunState,
        elapsed: Duration,
        value: f32,
        velocity: f32,
        target: f32,
    ) -> Self {
        Self {
            state,
            elapsed,
            value,
            velocity,
            target,
        }
    }

    /// Returns the sampled state.
    pub const fn state(self) -> MotionRunState {
        self.state
    }

    /// Returns the elapsed duration used for this sample.
    pub const fn elapsed(self) -> Duration {
        self.elapsed
    }

    /// Returns the sampled scalar value.
    pub const fn value(self) -> f32 {
        self.value
    }

    /// Returns the sampled scalar velocity.
    pub const fn velocity(self) -> f32 {
        self.velocity
    }

    /// Returns the target scalar value.
    pub const fn target(self) -> f32 {
        self.target
    }

    /// Returns whether callers should continue requesting frames.
    pub const fn is_active(self) -> bool {
        self.state.is_active()
    }

    /// Returns whether the semantic final state has been reached.
    pub const fn reached_final_state(self) -> bool {
        self.state.reached_final_state()
    }
}

/// A deterministic scalar spring transition.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MotionSpring {
    spec: MotionSpringSpec,
    from: f32,
    target: f32,
    initial_velocity: f32,
    started_at: Instant,
    cancelled_at: Option<Instant>,
}

impl MotionSpring {
    /// Creates a scalar spring transition.
    pub fn new(
        spec: MotionSpringSpec,
        from: f32,
        target: f32,
        initial_velocity: f32,
        started_at: Instant,
    ) -> Self {
        let from = sanitize_number(from, 0.0);
        Self {
            spec,
            from,
            target: sanitize_number(target, from),
            initial_velocity: sanitize_number(initial_velocity, 0.0),
            started_at,
            cancelled_at: None,
        }
    }

    /// Creates a new spring whose source and velocity come from an interrupted sample.
    pub fn retarget_from_sample(
        spec: MotionSpringSpec,
        sample: MotionScalarSample,
        target: f32,
        started_at: Instant,
    ) -> Self {
        Self::new(spec, sample.value(), target, sample.velocity(), started_at)
    }

    /// Returns the spring specification.
    pub const fn spec(self) -> MotionSpringSpec {
        self.spec
    }

    /// Returns the source value.
    pub const fn from(self) -> f32 {
        self.from
    }

    /// Returns the target value.
    pub const fn target(self) -> f32 {
        self.target
    }

    /// Returns the initial velocity.
    pub const fn initial_velocity(self) -> f32 {
        self.initial_velocity
    }

    /// Returns the instant at which the spring started.
    pub const fn started_at(self) -> Instant {
        self.started_at
    }

    /// Returns the instant at which the spring was cancelled.
    pub const fn cancelled_at(self) -> Option<Instant> {
        self.cancelled_at
    }

    /// Marks the spring as cancelled at the provided instant.
    pub fn cancel_at(&mut self, cancelled_at: Instant) {
        self.cancelled_at = Some(cancelled_at);
    }

    /// Samples the spring at the provided instant.
    pub fn sample(self, now: Instant) -> MotionScalarSample {
        let effective_now = self.cancelled_at.unwrap_or(now);
        let elapsed = effective_now.saturating_duration_since(self.started_at);
        let mut sample = Self::sample_elapsed(
            self.spec,
            self.from,
            self.target,
            self.initial_velocity,
            elapsed,
        );
        if self.cancelled_at.is_some() && !sample.reached_final_state() {
            sample.state = MotionRunState::Cancelled;
        }
        sample
    }

    /// Samples a spring using an explicit elapsed duration.
    pub fn sample_elapsed(
        spec: MotionSpringSpec,
        from: f32,
        target: f32,
        initial_velocity: f32,
        elapsed: Duration,
    ) -> MotionScalarSample {
        let from = sanitize_number(from, 0.0);
        let target = sanitize_number(target, from);
        let initial_velocity = sanitize_number(initial_velocity, 0.0);

        if spec.is_immediate() {
            return MotionScalarSample::new(
                MotionRunState::Immediate,
                elapsed,
                target,
                0.0,
                target,
            );
        }

        let physics = spec.physics();
        if elapsed.is_zero() {
            let state = if at_rest(from, target, initial_velocity, physics) {
                MotionRunState::Completed
            } else {
                MotionRunState::Active
            };
            let value = if state.reached_final_state() {
                target
            } else {
                from
            };
            let velocity = if state.reached_final_state() {
                0.0
            } else {
                initial_velocity
            };
            return MotionScalarSample::new(state, elapsed, value, velocity, target);
        }

        let (value, velocity) =
            sample_spring_value(physics, from, target, initial_velocity, elapsed);
        if at_rest(value, target, velocity, physics) {
            MotionScalarSample::new(MotionRunState::Completed, elapsed, target, 0.0, target)
        } else {
            MotionScalarSample::new(MotionRunState::Active, elapsed, value, velocity, target)
        }
    }
}

/// Shared motion model wrapper for timeline and spring transitions.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MotionModel {
    /// Duration/easing timeline motion.
    Timeline(MotionSpec),
    /// Velocity-aware spring motion.
    Spring(MotionSpringSpec),
}

impl MotionModel {
    /// Creates a timeline motion model.
    pub const fn timeline(spec: MotionSpec) -> Self {
        Self::Timeline(spec)
    }

    /// Creates a spring motion model.
    pub const fn spring(spec: MotionSpringSpec) -> Self {
        Self::Spring(spec)
    }

    /// Returns the motion preference.
    pub const fn preference(self) -> MotionPreference {
        match self {
            Self::Timeline(spec) => spec.preference(),
            Self::Spring(spec) => spec.preference(),
        }
    }

    /// Returns whether this model completes immediately.
    pub const fn is_immediate(self) -> bool {
        match self {
            Self::Timeline(spec) => spec.is_immediate(),
            Self::Spring(spec) => spec.is_immediate(),
        }
    }

    /// Returns the duration used when this model participates in a sequence plan.
    ///
    /// Timeline models use their exact duration. Spring models use their review-duration hint,
    /// because physical completion is still determined by sampled rest state.
    pub const fn sequence_duration_hint(self) -> Duration {
        match self {
            Self::Timeline(spec) => spec.duration().as_duration(),
            Self::Spring(spec) => spec.physics().review_duration(),
        }
    }

    /// Samples this motion model as a scalar value.
    pub fn sample_scalar_elapsed(
        self,
        from: f32,
        target: f32,
        initial_velocity: f32,
        elapsed: Duration,
    ) -> MotionScalarSample {
        match self {
            Self::Timeline(spec) => {
                let sample = MotionTimeline::sample_elapsed(spec, elapsed);
                let from = sanitize_number(from, 0.0);
                let target = sanitize_number(target, from);
                let value = from + (target - from) * sample.progress();
                let duration = spec.duration().as_duration().as_secs_f32();
                let velocity = if sample.reached_final_state() || duration <= 0.0 {
                    0.0
                } else {
                    (target - from) / duration
                };
                MotionScalarSample::new(sample.state(), sample.elapsed(), value, velocity, target)
            }
            Self::Spring(spec) => {
                MotionSpring::sample_elapsed(spec, from, target, initial_velocity, elapsed)
            }
        }
    }
}

fn sample_spring_value(
    physics: MotionSpringPhysics,
    from: f32,
    target: f32,
    initial_velocity: f32,
    elapsed: Duration,
) -> (f32, f32) {
    let t = elapsed.as_secs_f32().max(0.0);
    let displacement = from - target;
    let mass = physics.mass();
    let stiffness = physics.stiffness();
    let damping = physics.damping();
    let angular_frequency = (stiffness / mass).sqrt();
    let critical_damping = 2.0 * (stiffness * mass).sqrt();
    let damping_ratio = if critical_damping > 0.0 {
        damping / critical_damping
    } else {
        1.0
    };

    let (displacement, velocity) = if damping_ratio < 1.0 {
        sample_underdamped(
            displacement,
            initial_velocity,
            angular_frequency,
            damping_ratio,
            t,
        )
    } else if (damping_ratio - 1.0).abs() <= f32::EPSILON {
        sample_critically_damped(displacement, initial_velocity, angular_frequency, t)
    } else {
        sample_overdamped(
            displacement,
            initial_velocity,
            angular_frequency,
            damping_ratio,
            t,
        )
    };

    let value = sanitize_number(target + displacement, target);
    let velocity = sanitize_number(velocity, 0.0);
    (value, velocity)
}

fn sample_underdamped(
    displacement: f32,
    velocity: f32,
    angular_frequency: f32,
    damping_ratio: f32,
    time: f32,
) -> (f32, f32) {
    let damped_frequency = angular_frequency * (1.0 - damping_ratio * damping_ratio).sqrt();
    if damped_frequency <= MIN_POSITIVE {
        return sample_critically_damped(displacement, velocity, angular_frequency, time);
    }

    let decay = (-damping_ratio * angular_frequency * time).exp();
    let sin = (damped_frequency * time).sin();
    let cos = (damped_frequency * time).cos();
    let a = displacement;
    let b = (velocity + damping_ratio * angular_frequency * displacement) / damped_frequency;
    let oscillation = a * cos + b * sin;
    let sampled_displacement = decay * oscillation;
    let sampled_velocity = decay
        * ((-a * damped_frequency * sin + b * damped_frequency * cos)
            - damping_ratio * angular_frequency * oscillation);
    (sampled_displacement, sampled_velocity)
}

fn sample_critically_damped(
    displacement: f32,
    velocity: f32,
    angular_frequency: f32,
    time: f32,
) -> (f32, f32) {
    let decay = (-angular_frequency * time).exp();
    let c = velocity + angular_frequency * displacement;
    let displacement_term = displacement + c * time;
    let sampled_displacement = decay * displacement_term;
    let sampled_velocity = decay * (c - angular_frequency * displacement_term);
    (sampled_displacement, sampled_velocity)
}

fn sample_overdamped(
    displacement: f32,
    velocity: f32,
    angular_frequency: f32,
    damping_ratio: f32,
    time: f32,
) -> (f32, f32) {
    let ratio_delta = (damping_ratio * damping_ratio - 1.0).sqrt();
    let r1 = -angular_frequency * (damping_ratio - ratio_delta);
    let r2 = -angular_frequency * (damping_ratio + ratio_delta);
    if (r1 - r2).abs() <= MIN_POSITIVE {
        return sample_critically_damped(displacement, velocity, angular_frequency, time);
    }
    let c1 = (velocity - r2 * displacement) / (r1 - r2);
    let c2 = displacement - c1;
    let e1 = (r1 * time).exp();
    let e2 = (r2 * time).exp();
    let sampled_displacement = c1 * e1 + c2 * e2;
    let sampled_velocity = c1 * r1 * e1 + c2 * r2 * e2;
    (sampled_displacement, sampled_velocity)
}

fn at_rest(value: f32, target: f32, velocity: f32, physics: MotionSpringPhysics) -> bool {
    (value - target).abs() <= physics.rest_delta() && velocity.abs() <= physics.rest_speed()
}

fn sanitize_number(value: f32, default: f32) -> f32 {
    if value.is_finite() { value } else { default }
}

fn sanitize_positive(value: f32, default: f32) -> f32 {
    if value.is_finite() && value > 0.0 {
        value.clamp(MIN_POSITIVE, MAX_PHYSICS_VALUE)
    } else {
        default
    }
}

fn sanitize_non_negative(value: f32, default: f32) -> f32 {
    if value.is_finite() && value >= 0.0 {
        value.clamp(0.0, MAX_PHYSICS_VALUE)
    } else {
        default
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::MotionPreference;
    use std::time::{Duration, Instant};

    #[test]
    fn layout_spring_samples_active_motion_and_reaches_exact_target_at_rest() {
        let started_at = Instant::now();
        let spring = MotionSpring::new(
            MotionSpringSpec::layout(MotionPreference::Animated),
            0.0,
            1.0,
            0.0,
            started_at,
        );

        let start = spring.sample(started_at);
        assert_eq!(start.state(), MotionRunState::Active);
        assert_eq!(start.elapsed(), Duration::ZERO);
        assert_eq!(start.value(), 0.0);
        assert_eq!(start.target(), 1.0);

        let midpoint = spring.sample(started_at + Duration::from_millis(90));
        assert_eq!(midpoint.state(), MotionRunState::Active);
        assert!(midpoint.value() > 0.0);
        assert!(midpoint.value() < 1.08);
        assert!(midpoint.velocity().is_finite());

        let complete = spring.sample(started_at + Duration::from_secs(2));
        assert_eq!(complete.state(), MotionRunState::Completed);
        assert_eq!(complete.value(), 1.0);
        assert_eq!(complete.velocity(), 0.0);
        assert!(complete.reached_final_state());
    }

    #[test]
    fn tiny_delta_uses_rest_thresholds_without_oscillating_forever() {
        let sample = MotionSpring::sample_elapsed(
            MotionSpringSpec::layout(MotionPreference::Animated),
            10.0,
            10.0001,
            0.0,
            Duration::from_millis(600),
        );

        assert_eq!(sample.state(), MotionRunState::Completed);
        assert_eq!(sample.value(), 10.0001);
    }

    #[test]
    fn spring_bounce_defaults_are_subtle_and_clamped() {
        let layout = MotionSpringSpec::layout(MotionPreference::Animated);
        assert!(layout.physics().bounce() <= 0.20);

        let clamped = layout.with_bounce(2.0);
        assert!(clamped.physics().bounce() <= MotionSpringPhysics::MAX_REVIEWABLE_BOUNCE);
    }

    #[test]
    fn retargeted_spring_preserves_current_position_and_velocity() {
        let started_at = Instant::now();
        let spec = MotionSpringSpec::layout(MotionPreference::Animated);
        let spring = MotionSpring::new(spec, 0.0, 1.0, 0.0, started_at);
        let sampled_at = started_at + Duration::from_millis(80);
        let sampled = spring.sample(sampled_at);

        let retargeted = MotionSpring::retarget_from_sample(spec, sampled, 2.0, sampled_at);
        let retarget_start = retargeted.sample(sampled_at);

        assert_eq!(retarget_start.value(), sampled.value());
        assert_eq!(retarget_start.velocity(), sampled.velocity());
        assert_eq!(retarget_start.target(), 2.0);
    }

    #[test]
    fn reduced_motion_spring_returns_final_semantic_sample() {
        let sample = MotionSpring::sample_elapsed(
            MotionSpringSpec::layout(MotionPreference::Reduced),
            0.0,
            1.0,
            20.0,
            Duration::from_millis(16),
        );

        assert_eq!(sample.state(), MotionRunState::Immediate);
        assert_eq!(sample.value(), 1.0);
        assert_eq!(sample.velocity(), 0.0);
        assert!(sample.reached_final_state());
    }

    #[test]
    fn invalid_physics_parameters_are_sanitized() {
        let physics = MotionSpringPhysics::new(f32::NAN, -1.0, f32::INFINITY)
            .with_rest_delta(f32::NAN)
            .with_rest_speed(-20.0);
        let sample = MotionSpring::sample_elapsed(
            MotionSpringSpec::from_physics(MotionPreference::Animated, physics),
            0.0,
            1.0,
            f32::NAN,
            Duration::from_millis(80),
        );

        assert!(sample.value().is_finite());
        assert!(sample.velocity().is_finite());
    }

    #[test]
    fn motion_model_wraps_timeline_and_spring_specs() {
        let timeline = MotionModel::timeline(crate::MotionSpec::layout(MotionPreference::Animated));
        let spring = MotionModel::spring(MotionSpringSpec::layout(MotionPreference::Animated));

        assert!(!timeline.is_immediate());
        assert!(!spring.is_immediate());
        assert_eq!(spring.preference(), MotionPreference::Animated);
    }

    #[test]
    fn motion_preset_resolves_default_springs_explicitly() {
        let custom_timeline = MotionPreset::timeline(crate::MotionSpec::new(
            MotionPreference::Animated,
            crate::MotionDuration::Custom(Duration::from_millis(240)),
            crate::MotionEasing::Linear,
        ))
        .resolve_model();
        assert!(matches!(custom_timeline, MotionModel::Timeline(_)));

        let committed = MotionPreset::committed_layout(MotionPreference::Animated).resolve_model();
        assert!(matches!(
            committed,
            MotionModel::Spring(spec)
                if spec.preset() == Some(MotionSpringPreset::Layout)
        ));

        let continuity = MotionPreset::continuity(MotionPreference::Animated).resolve_model();
        assert!(matches!(
            continuity,
            MotionModel::Spring(spec)
                if spec.preset() == Some(MotionSpringPreset::Continuity)
        ));
    }

    #[test]
    fn motion_model_samples_timeline_and_spring_as_scalar_values() {
        let timeline = MotionModel::timeline(crate::MotionSpec::new(
            MotionPreference::Animated,
            crate::MotionDuration::Custom(Duration::from_millis(200)),
            crate::MotionEasing::Linear,
        ));
        let timeline_sample =
            timeline.sample_scalar_elapsed(0.0, 10.0, 0.0, Duration::from_millis(100));

        assert_eq!(timeline_sample.state(), MotionRunState::Active);
        assert_eq!(timeline_sample.value(), 5.0);
        assert_eq!(timeline_sample.target(), 10.0);

        let spring = MotionModel::spring(MotionSpringSpec::layout(MotionPreference::Animated));
        let spring_sample =
            spring.sample_scalar_elapsed(0.0, 10.0, 0.0, Duration::from_millis(100));

        assert_eq!(spring_sample.state(), MotionRunState::Active);
        assert!(spring_sample.value() > 0.0);
        assert_eq!(spring_sample.target(), 10.0);
        assert!(spring_sample.velocity().is_finite());
    }
}