gpui-m3 0.2.4

Material 3 Expressive components for GPUI: shape morphing, spring motion and dynamic color
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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
//! M3 Expressive motion: physics-based springs (not fixed-duration curves).
//!
//! The values are the official ones from `androidx.compose.material3` (`MotionScheme.expressive()`):
//! spatial springs for position, size and shape (with bounce) and effects springs for color and opacity (no bounce).
//! When the target changes mid-flight the spring keeps its velocity, as in Compose.
//!
//! GPUI does not support curves that overshoot 1 in `with_animation`, so components
//! animate with [`animate`], which keeps the spring state between frames.

use std::{
    cell::RefCell,
    collections::{HashMap, HashSet},
    time::{Duration, Instant},
};

use gpui::{App, ElementId, EntityId, Global, Hsla, Pixels, Rgba, Styled, Window, WindowId, px};

/// Unit-mass spring: stiffness and damping ratio.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Spring {
    pub stiffness: f32,
    pub damping_ratio: f32,
}

impl Spring {
    pub const SPATIAL_FAST: Spring = Spring {
        stiffness: 800.,
        damping_ratio: 0.6,
    };
    pub const SPATIAL: Spring = Spring {
        stiffness: 380.,
        damping_ratio: 0.8,
    };
    pub const SPATIAL_SLOW: Spring = Spring {
        stiffness: 200.,
        damping_ratio: 0.8,
    };
    pub const EFFECTS_FAST: Spring = Spring {
        stiffness: 3800.,
        damping_ratio: 1.,
    };
    pub const EFFECTS: Spring = Spring {
        stiffness: 1600.,
        damping_ratio: 1.,
    };
    pub const EFFECTS_SLOW: Spring = Spring {
        stiffness: 800.,
        damping_ratio: 1.,
    };

    /// Displacement and velocity after `t` seconds, starting from `x0` (relative to the target) with velocity `v0`.
    pub fn solve(self, x0: f32, v0: f32, t: f32) -> (f32, f32) {
        let w0 = self.stiffness.sqrt();
        let z = self.damping_ratio;
        if z < 1. {
            let wd = w0 * (1. - z * z).sqrt();
            let decay = (-z * w0 * t).exp();
            let a = x0;
            let b = (v0 + z * w0 * x0) / wd;
            let (sin, cos) = (wd * t).sin_cos();
            let x = decay * (a * cos + b * sin);
            let v = decay * ((b * wd - z * w0 * a) * cos - (a * wd + z * w0 * b) * sin);
            (x, v)
        } else {
            let decay = (-w0 * t).exp();
            let b = v0 + w0 * x0;
            ((x0 + b * t) * decay, (v0 - w0 * b * t) * decay)
        }
    }

    /// Step response (0 → 1) after `t` seconds. May exceed 1 (bounce).
    pub fn step(self, t: f32) -> f32 {
        1. - self.solve(1., 0., t).0
    }

    /// Approximate time to settle (step response within 0.1 %).
    pub fn settle_time(self) -> Duration {
        let w0 = self.stiffness.sqrt();
        let z = self.damping_ratio;
        let seconds = if z < 1. {
            // The oscillation envelope starts at 1/sqrt(1 - z²), not at 1.
            (1000. / (1. - z * z).sqrt()).ln() / (z * w0)
        } else {
            // Critically damped: (1 + w0·t)·e^(-w0·t) drops below 0.1% at w0·t ≈ 9.23.
            9.25 / w0
        };
        Duration::from_secs_f32(seconds)
    }
}

/// Global motion settings. `time_scale` > 1 slows everything down (useful for reviewing animations).
#[derive(Clone, Copy, Debug)]
pub struct MotionSettings {
    pub time_scale: f32,
    pub reduced: bool,
}

impl Default for MotionSettings {
    fn default() -> Self {
        Self {
            time_scale: 1.,
            reduced: false,
        }
    }
}

impl Global for MotionSettings {}

impl MotionSettings {
    pub fn get(cx: &App) -> MotionSettings {
        cx.try_global::<MotionSettings>()
            .copied()
            .unwrap_or_default()
    }

    /// Follows the system's reduced motion setting: stores `reduced` and redraws every window,
    /// but only when it changed (call it when a window activates, not every frame). Returns
    /// whether it changed.
    pub fn sync(reduced: bool, cx: &mut App) -> bool {
        let current = Self::get(cx);
        if current.reduced == reduced && cx.has_global::<MotionSettings>() {
            return false;
        }
        cx.set_global(MotionSettings {
            reduced,
            ..current
        });
        cx.refresh_windows();
        true
    }
}

/// Seconds elapsed since `start`, in animation time (applying `time_scale`).
pub fn elapsed(start: Instant, cx: &App) -> f32 {
    start.elapsed().as_secs_f32() / MotionSettings::get(cx).time_scale.max(0.01)
}

/// Shared clock for continuous animations (loading indicators, breathing shapes).
pub fn clock(cx: &App) -> f32 {
    static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
    elapsed(*START.get_or_init(Instant::now), cx)
}

/// Who asks for frames: each call site of the motion helpers that keeps the window animating,
/// counted until [`take_frame_requests`] reads them. Lets an app find what keeps it redrawing.
/// Only with the `frame-stats` feature: otherwise nothing is counted.
#[cfg(feature = "frame-stats")]
static FRAME_REQUESTS: std::sync::Mutex<Vec<(&'static std::panic::Location<'static>, u32)>> =
    std::sync::Mutex::new(Vec::new());

#[track_caller]
pub(crate) fn request_frame(window: &mut Window) {
    count_frame_request();
    window.request_animation_frame();
}

/// `window.request_animation_frame()`, counted by [`take_frame_requests`] at the caller's
/// line like the frames of the motion helpers. For an app's own frame-by-frame animation, so
/// a window that keeps redrawing shows who asked.
#[track_caller]
pub fn request_animation_frame(window: &mut Window) {
    request_frame(window);
}

/// [`request_frame`] for the element `id`: with `frame-stats`, [`take_frame_requests`] also
/// says which element asked most from each call site (one call site serves every row of a
/// list, and the row is what you need to find).
#[track_caller]
pub(crate) fn request_frame_for(window: &mut Window, label: &FrameLabel) {
    #[cfg(feature = "frame-stats")]
    note_frame_id(std::panic::Location::caller(), label);
    #[cfg(not(feature = "frame-stats"))]
    let _ = label;
    request_frame(window);
}

/// The id [`request_frame_for`] reports: kept only with `frame-stats` (nothing to clone
/// otherwise).
#[cfg(feature = "frame-stats")]
pub(crate) type FrameLabel = ElementId;
#[cfg(not(feature = "frame-stats"))]
pub(crate) type FrameLabel = ();

pub(crate) fn frame_label(id: &ElementId) -> FrameLabel {
    #[cfg(feature = "frame-stats")]
    {
        id.clone()
    }
    #[cfg(not(feature = "frame-stats"))]
    {
        let _ = id;
    }
}

/// Distinct elements remembered per call site between two [`take_frame_requests`].
#[cfg(feature = "frame-stats")]
const FRAME_IDS_MAX: usize = 16;

#[cfg(feature = "frame-stats")]
type FrameIds = Vec<(&'static std::panic::Location<'static>, Vec<(ElementId, u32)>)>;

#[cfg(feature = "frame-stats")]
thread_local! {
    /// Per call site, the elements that requested frames from it (see [`request_frame_for`]).
    static FRAME_IDS: RefCell<FrameIds> = const { RefCell::new(Vec::new()) };
}

#[cfg(feature = "frame-stats")]
fn note_frame_id(at: &'static std::panic::Location<'static>, id: &ElementId) {
    FRAME_IDS.with(|sites| {
        let mut sites = sites.borrow_mut();
        let ids = match sites.iter_mut().position(|(loc, _)| std::ptr::eq(*loc, at)) {
            Some(i) => &mut sites[i].1,
            None => {
                sites.push((at, Vec::new()));
                &mut sites.last_mut().expect("just pushed").1
            }
        };
        if let Some((_, n)) = ids.iter_mut().find(|(seen, _)| seen == id) {
            *n += 1;
        } else if ids.len() < FRAME_IDS_MAX {
            ids.push((id.clone(), 1));
        }
    });
}

/// Counts a frame request from the caller's call site (see [`take_frame_requests`]). The
/// timed redraws of [`continuous_at`] count too: they are frames as much as an animation
/// frame, and without them a window kept busy by spinners showed no culprit.
#[track_caller]
fn count_frame_request() {
    #[cfg(feature = "frame-stats")]
    {
        let at = std::panic::Location::caller();
        if let Ok(mut list) = FRAME_REQUESTS.lock() {
            match list.iter_mut().find(|(loc, _)| std::ptr::eq(*loc, at)) {
                Some((_, n)) => *n += 1,
                None => list.push((at, 1)),
            }
        }
    }
}

/// Shared grid for timed redraws, in ticks per second. Every [`tick_delay`] lands on it, so a
/// spinner at 30 fps, a caret at 4 fps and an app's coalesced updates fire at the same
/// instants and GPUI draws them in one frame instead of interleaving them (30 + 33 updates
/// per second used to be ~50 frames).
const TICK_GRID: f64 = 60.;

/// Start of the tick grid (not scaled by the motion settings: it paces timers, not values).
fn tick_origin() -> Instant {
    static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
    *START.get_or_init(Instant::now)
}

/// Time until the next tick of a `fps` ticker on the shared grid. Use it to pace redraws that
/// do not need every frame (streamed text, clocks): `fps` ticks per second at most, in step
/// with the motion helpers' own timed redraws.
pub fn tick_delay(fps: f32) -> Duration {
    let now = tick_origin().elapsed().as_secs_f64();
    Duration::from_secs_f64(delay_to_tick(now, fps as f64))
}

/// Seconds from `now` (seconds since the grid origin) to the next multiple of `1 / fps`,
/// moved forward onto the [`TICK_GRID`] when that multiple is not on it. Never zero, so a
/// redraw that lands right on a tick waits for the next one instead of firing twice.
fn delay_to_tick(now: f64, fps: f64) -> f64 {
    let period = 1. / fps.clamp(0.1, TICK_GRID);
    let mut next = ((now / period).floor() + 1.) * period;
    if next - now < 1e-4 {
        // `now` is on a tick (float error put it just before): the next one.
        next += period;
    }
    // The epsilon keeps a tick that is already on the grid (k/30 → 2k/60) from rounding a
    // whole grid step up because of float error.
    let next = ((next * TICK_GRID) - 1e-6).ceil() / TICK_GRID;
    (next - now).max(1e-4)
}

/// The frame requests since the last call, as `file:line` and count, most frequent first.
/// When the call site animates elements by id, the one that asked most follows in brackets
/// with its own count (`file:line [row-12 ×40]`). Always empty without the `frame-stats`
/// feature.
pub fn take_frame_requests() -> Vec<(String, u32)> {
    #[cfg(feature = "frame-stats")]
    {
        let Ok(mut list) = FRAME_REQUESTS.lock() else {
            return Vec::new();
        };
        let ids = FRAME_IDS.with(|sites| std::mem::take(&mut *sites.borrow_mut()));
        let mut out: Vec<(String, u32)> = list
            .drain(..)
            .map(|(at, n)| {
                let top = ids
                    .iter()
                    .find(|(loc, _)| std::ptr::eq(*loc, at))
                    .and_then(|(_, ids)| ids.iter().max_by_key(|(_, n)| *n));
                let site = match top {
                    Some((id, k)) => format!("{}:{} [{id} ×{k}]", at.file(), at.line()),
                    None => format!("{}:{}", at.file(), at.line()),
                };
                (site, n)
            })
            .collect();
        out.sort_by_key(|entry| std::cmp::Reverse(entry.1));
        out
    }
    #[cfg(not(feature = "frame-stats"))]
    Vec::new()
}

/// Clock for a continuous animation: requests the next frame and returns the current time.
/// With reduced motion it always returns 0 and requests no frames (the animation stays still).
#[track_caller]
pub fn continuous(window: &mut Window, cx: &App) -> f32 {
    if MotionSettings::get(cx).reduced {
        return 0.;
    }
    request_frame(window);
    clock(cx)
}

/// Frame rate cap for [`continuous_at`] while its window is not the active one.
const BACKGROUND_FPS: f32 = 4.;

thread_local! {
    /// Views that already have a redraw scheduled by [`continuous_at`] (avoids piling up timers).
    static PENDING: RefCell<HashSet<EntityId>> = RefCell::new(HashSet::new());
    /// Per window, the ambient clock of [`ambient_clock`].
    static AMBIENT: RefCell<HashMap<WindowId, Ambient>> = RefCell::new(HashMap::new());
}

struct Ambient {
    real: f32,
    shown: f32,
    active: bool,
    held: bool,
}

impl Ambient {
    fn new(now: f32, active: bool) -> Self {
        Ambient {
            real: now,
            shown: now,
            active,
            held: false,
        }
    }

    /// Moves the clock to `now` and returns the time to show. It advances only while the window
    /// stays active and nothing holds it, and the first call after a hold does not advance, so
    /// the shapes resume from the pose they held instead of jumping ahead.
    fn advance(&mut self, now: f32, active: bool, held: bool) -> f32 {
        // A long gap (nothing was drawing it) is not time the shapes should catch up on.
        if active && self.active && !held && !self.held {
            self.shown += (now - self.real).clamp(0., 0.5);
        }
        self.real = now;
        self.active = active;
        self.held = held;
        self.shown
    }
}

/// Clock for slow ambient motion that stops while the window is in the background and
/// resumes from where it was, so the shapes neither jump to their first pose when focus
/// changes nor leap ahead when it returns. 0 with reduced motion.
pub fn ambient_clock(window: &Window, cx: &App) -> f32 {
    ambient_tick(window, cx, false)
}

/// [`ambient_clock`] held still: returns the pose it was at and keeps it there (see
/// [`crate::Shape::ambient`]).
pub(crate) fn held_ambient_clock(window: &Window, cx: &App) -> f32 {
    ambient_tick(window, cx, true)
}

fn ambient_tick(window: &Window, cx: &App, held: bool) -> f32 {
    if MotionSettings::get(cx).reduced {
        return 0.;
    }
    let now = clock(cx);
    let active = window.is_window_active();
    AMBIENT.with(|map| {
        map.borrow_mut()
            .entry(window.window_handle().window_id())
            .or_insert_with(|| Ambient::new(now, active))
            .advance(now, active, held)
    })
}

/// Like [`continuous`], but at `fps` frames per second. For slow ambient motion
/// (shapes that breathe or rotate slowly) 30 fps looks the same and costs half as much.
#[track_caller]
pub fn continuous_at(fps: f32, window: &mut Window, cx: &mut App) -> f32 {
    if MotionSettings::get(cx).reduced {
        return 0.;
    }
    // In a background window it keeps moving (it may still be on screen), but slower:
    // every tick redraws the whole view, not just the 16 px spinner.
    let fps = if window.is_window_active() {
        fps
    } else {
        fps.min(BACKGROUND_FPS)
    };
    if fps >= 60. {
        request_frame(window);
        return clock(cx);
    }
    let view = window.current_view();
    if PENDING.with(|p| p.borrow_mut().insert(view)) {
        count_frame_request();
        // On the shared grid: other timed redraws of this window land on the same frame.
        let timer = cx.background_executor().timer(tick_delay(fps.max(1.)));
        cx.spawn(async move |cx| {
            timer.await;
            PENDING.with(|p| p.borrow_mut().remove(&view));
            cx.update(|cx| cx.notify(view)).ok();
        })
        .detach();
    }
    clock(cx)
}

/// State of an `N`-channel value that follows its target with a spring.
#[derive(Clone, Debug)]
pub struct SpringValue<const N: usize> {
    spring: Spring,
    target: [f32; N],
    offset: [f32; N],
    velocity: [f32; N],
    start: Instant,
    settled: bool,
}

impl<const N: usize> SpringValue<N> {
    pub fn new(spring: Spring, value: [f32; N]) -> Self {
        Self {
            spring,
            target: value,
            offset: [0.; N],
            velocity: [0.; N],
            start: Instant::now(),
            settled: true,
        }
    }

    /// Current value and velocity.
    fn sample(&self, t: f32) -> ([f32; N], [f32; N]) {
        let mut value = self.target;
        let mut velocity = [0.; N];
        if !self.settled {
            for i in 0..N {
                let (x, v) = self.spring.solve(self.offset[i], self.velocity[i], t);
                value[i] = self.target[i] + x;
                velocity[i] = v;
            }
        }
        (value, velocity)
    }

    /// Advances to the current instant; returns the value and whether it is still moving.
    pub fn update(
        &mut self,
        target: [f32; N],
        spring: Spring,
        t: f32,
        now: Instant,
    ) -> ([f32; N], bool) {
        if target != self.target || spring != self.spring {
            let (value, velocity) = self.sample(t);
            for i in 0..N {
                self.offset[i] = value[i] - target[i];
                self.velocity[i] = velocity[i];
            }
            self.target = target;
            self.spring = spring;
            self.start = now;
            self.settled = false;
            return (value, true);
        }
        if self.settled {
            return (self.target, false);
        }
        let (value, velocity) = self.sample(t);
        let resting =
            (0..N).all(|i| (value[i] - self.target[i]).abs() < 0.002 && velocity[i].abs() < 0.05);
        if resting {
            self.settled = true;
            return (self.target, false);
        }
        (value, true)
    }

    /// Launches the value from `from` toward the current target (for entrance animations).
    pub fn kick(&mut self, from: [f32; N], now: Instant) {
        for (offset, (from, target)) in self.offset.iter_mut().zip(from.iter().zip(&self.target)) {
            *offset = from - target;
        }
        self.velocity = [0.; N];
        self.start = now;
        self.settled = false;
    }
}

/// Animates `target` with a spring and returns this frame's value.
///
/// `id` identifies the value across frames (must be unique within the view). The first frame
/// returns the target directly; use [`animate_from`] to animate the entrance.
#[track_caller]
pub fn animate<const N: usize>(
    id: impl Into<ElementId>,
    spring: Spring,
    target: [f32; N],
    window: &mut Window,
    cx: &mut App,
) -> [f32; N] {
    animate_inner(id.into(), spring, target, None, window, cx)
}

/// Like [`animate`], but the first frame starts from `from` (spring entrance).
#[track_caller]
pub fn animate_from<const N: usize>(
    id: impl Into<ElementId>,
    spring: Spring,
    from: [f32; N],
    target: [f32; N],
    window: &mut Window,
    cx: &mut App,
) -> [f32; N] {
    animate_inner(id.into(), spring, target, Some(from), window, cx)
}

#[track_caller]
fn animate_inner<const N: usize>(
    id: ElementId,
    spring: Spring,
    target: [f32; N],
    from: Option<[f32; N]>,
    window: &mut Window,
    cx: &mut App,
) -> [f32; N] {
    let settings = MotionSettings::get(cx);
    let label = frame_label(&id);
    let (value, moving) = element_state(id, window, |state: Option<SpringValue<N>>, _| {
        let mut s = state.unwrap_or_else(|| {
            let mut value = SpringValue::new(spring, target);
            if let Some(from) = from {
                value.kick(from, Instant::now());
            }
            value
        });
        if settings.reduced {
            return ((target, false), SpringValue::new(spring, target));
        }
        // Shortcut: a value at rest with the same target needs no computation.
        if s.settled && s.target == target && s.spring == spring {
            return ((target, false), s);
        }
        let now = Instant::now();
        let t = now.duration_since(s.start).as_secs_f32() / settings.time_scale.max(0.01);
        // Retargeted again right after starting: two live elements share this id and keep
        // flipping each other's target every frame, so the window never stops redrawing.
        #[cfg(feature = "frame-stats")]
        if (target != s.target || spring != s.spring) && t < 0.004 {
            log::warn!("spring {label:?} retargeted twice within a frame (duplicate element id)");
        }
        (s.update(target, spring, t, now), s)
    });
    if moving {
        request_frame_for(window, &label);
    }
    value
}

/// Plain state tied to `id` that lives as long as the element is drawn in consecutive frames.
/// Lighter than `use_keyed_state` (creates no entity or observer).
pub(crate) fn element_state<S: 'static, R>(
    id: ElementId,
    window: &mut Window,
    f: impl FnOnce(Option<S>, &mut Window) -> (R, S),
) -> R {
    window.with_global_id(id, |global_id, window| {
        window.with_element_state(global_id, f)
    })
}

struct Triggered<const N: usize> {
    value: SpringValue<N>,
    active: bool,
}

/// Each time `active` goes from `false` to `true`, the value jumps to `from` and springs back
/// to `rest` (e.g. the icon that "pops" when a tab is selected).
#[track_caller]
pub fn animate_on_activate<const N: usize>(
    id: impl Into<ElementId>,
    spring: Spring,
    active: bool,
    from: [f32; N],
    rest: [f32; N],
    window: &mut Window,
    cx: &mut App,
) -> [f32; N] {
    let settings = MotionSettings::get(cx);
    let id = id.into();
    let label = frame_label(&id);
    let (value, moving) = element_state(id, window, |state: Option<Triggered<N>>, _| {
        let mut s = state.unwrap_or_else(|| {
            let mut value = SpringValue::new(spring, rest);
            // Anything already active when it appears also animates its entrance.
            if active {
                value.kick(from, Instant::now());
            }
            Triggered { value, active }
        });
        if settings.reduced {
            return ((rest, false), s);
        }
        let now = Instant::now();
        if active && !s.active {
            s.value.kick(from, now);
        }
        s.active = active;
        if s.value.settled && s.value.target == rest {
            return ((rest, false), s);
        }
        let t = now.duration_since(s.value.start).as_secs_f32() / settings.time_scale.max(0.01);
        (s.value.update(rest, spring, t, now), s)
    });
    if moving {
        request_frame_for(window, &label);
    }
    value
}

/// Entrance progress (0 → 1, with the spring's bounce) since the element appeared,
/// after `delay` seconds. Useful for staggering lists and menus.
#[track_caller]
pub fn entrance(
    id: impl Into<ElementId>,
    spring: Spring,
    delay: f32,
    window: &mut Window,
    cx: &mut App,
) -> f32 {
    let settings = MotionSettings::get(cx);
    let id = id.into();
    let label = frame_label(&id);
    let start = element_state(id, window, |start: Option<Instant>, _| {
        let start = start.unwrap_or_else(Instant::now);
        (start, start)
    });
    if settings.reduced {
        return 1.;
    }
    match entrance_progress(spring, elapsed(start, cx) - delay) {
        Some(p) => {
            request_frame_for(window, &label);
            p
        }
        None => 1.,
    }
}

/// Like [`entrance`], but from `start`, an instant the caller keeps (when a message arrived,
/// when an event happened) instead of when the element was first drawn. Drawing the element
/// again later (a list row that scrolls back into view, a view that is rebuilt) does not play
/// the entrance again, and showing it halfway through shows it halfway. Requests frames only
/// until it settles; 1 with reduced motion.
#[track_caller]
pub fn entrance_since(
    start: Instant,
    spring: Spring,
    delay: f32,
    window: &mut Window,
    cx: &App,
) -> f32 {
    if MotionSettings::get(cx).reduced {
        return 1.;
    }
    match entrance_progress(spring, elapsed(start, cx) - delay) {
        Some(p) => {
            request_frame(window);
            p
        }
        None => 1.,
    }
}

/// Progress of an entrance `t` seconds after it starts (negative: still waiting for its
/// delay), or `None` once it has settled and needs no more frames.
fn entrance_progress(spring: Spring, t: f32) -> Option<f32> {
    (t < spring.settle_time().as_secs_f32()).then(|| spring.step(t.max(0.)))
}

/// Shortcut for animating a single number.
#[track_caller]
pub fn animate_f32(
    id: impl Into<ElementId>,
    spring: Spring,
    target: f32,
    window: &mut Window,
    cx: &mut App,
) -> f32 {
    animate(id, spring, [target], window, cx)[0]
}

/// Shortcut for animating a length in pixels.
#[track_caller]
pub fn animate_px(
    id: impl Into<ElementId>,
    spring: Spring,
    target: Pixels,
    window: &mut Window,
    cx: &mut App,
) -> Pixels {
    px(animate(id, spring, [f32::from(target)], window, cx)[0])
}

/// Shortcut for animating a color (interpolated in sRGB; no bounce when using an effects spring).
#[track_caller]
pub fn animate_color(
    id: impl Into<ElementId>,
    spring: Spring,
    target: Hsla,
    window: &mut Window,
    cx: &mut App,
) -> Hsla {
    let c = Rgba::from(target);
    let [r, g, b, a] = animate(id, spring, [c.r, c.g, c.b, c.a], window, cx);
    Rgba {
        r: r.clamp(0., 1.),
        g: g.clamp(0., 1.),
        b: b.clamp(0., 1.),
        a: a.clamp(0., 1.),
    }
    .into()
}

/// Cubic Bézier curve (like CSS `cubic-bezier()`).
pub fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32) -> impl Fn(f32) -> f32 + Copy {
    move |x: f32| {
        if x <= 0. {
            return 0.;
        }
        if x >= 1. {
            return 1.;
        }
        let bez = |t: f32, a: f32, b: f32| {
            3. * a * t * (1. - t).powi(2) + 3. * b * t * t * (1. - t) + t.powi(3)
        };
        let (mut lo, mut hi) = (0f32, 1f32);
        let mut t = x;
        for _ in 0..24 {
            let v = bez(t, x1, x2);
            if (v - x).abs() < 1e-5 {
                break;
            }
            if v < x {
                lo = t;
            } else {
                hi = t;
            }
            t = (lo + hi) / 2.;
        }
        bez(t, y1, y2)
    }
}

/// Stable child key for a component's animated values.
/// Opacity for pulsing text ("Working…"): 1 → 0.45 → 1 every `period` seconds, at 30 fps.
/// With reduced motion it stays at 1.
#[track_caller]
pub fn pulse(period: f32, window: &mut Window, cx: &mut App) -> f32 {
    if MotionSettings::get(cx).reduced {
        return 1.;
    }
    let t = continuous_at(30., window, cx);
    0.725 + 0.275 * (t / period.max(0.1) * std::f32::consts::TAU).cos()
}

/// Time-based replay: returns the seconds elapsed since `generation` last changed, or `None`
/// once `duration` has passed (and on the first frame, so nothing plays on mount). Use it for
/// one-shot effects such as the send button's launch or a tab's content fading in.
#[track_caller]
pub fn replay(
    id: impl Into<ElementId>,
    generation: u64,
    duration: f32,
    window: &mut Window,
    cx: &mut App,
) -> Option<f32> {
    let settings = MotionSettings::get(cx);
    let id = id.into();
    let label = frame_label(&id);
    let start = element_state(
        id,
        window,
        |state: Option<(u64, Option<Instant>)>, _| {
            let state = match state {
                Some((g, start)) if g == generation => (g, start),
                Some(_) => (generation, Some(Instant::now())),
                None => (generation, None),
            };
            (state.1, state)
        },
    );
    if settings.reduced {
        return None;
    }
    let t = elapsed(start?, cx);
    (t < duration).then(|| {
        request_frame_for(window, &label);
        t
    })
}

/// Seconds since `active` last went from `false` to `true`, while fewer than `duration` have
/// passed; `None` otherwise (and when it starts active, so nothing plays on mount). Use it for
/// one-shot effects tied to a state edge, such as a shape that breathes once when hovered.
#[track_caller]
pub fn play_on_rise(
    id: impl Into<ElementId>,
    active: bool,
    duration: f32,
    window: &mut Window,
    cx: &mut App,
) -> Option<f32> {
    let settings = MotionSettings::get(cx);
    let id = id.into();
    let label = frame_label(&id);
    let start = element_state(
        id,
        window,
        |state: Option<(bool, Option<Instant>)>, _| {
            let state = match state {
                Some((false, _)) if active => (true, Some(Instant::now())),
                Some((_, start)) => (active, start),
                None => (active, None),
            };
            (state.1, state)
        },
    );
    if settings.reduced {
        return None;
    }
    let t = elapsed(start?, cx);
    (t < duration).then(|| {
        request_frame_for(window, &label);
        t
    })
}

/// Keeps something on screen while it animates out.
///
/// Returns `Some(progress)` while the content should be drawn: `1.` while `show` is true, then
/// falling to `0.` with the fast effects spring once `show` turns false (exits are shorter than
/// entrances). Returns `None` when the exit has finished or when it was never shown. Call it
/// every frame, shown or not, with the same `id`:
///
/// ```ignore
/// div().when_some(motion::presence("offer", self.offer.is_some(), window, cx), |d, p| {
///     d.child(banner(&self.last_offer).opacity(p))
/// })
/// ```
///
/// Keep the data of the leaving content (the last offer, the last menu) until it returns `None`.
#[track_caller]
pub fn presence(
    id: impl Into<ElementId>,
    show: bool,
    window: &mut Window,
    cx: &mut App,
) -> Option<f32> {
    let settings = MotionSettings::get(cx);
    let spring = Spring::EFFECTS_FAST;
    let id = id.into();
    let label = frame_label(&id);
    let (value, moving) = element_state(id, window, |state: Option<Presence>, _| {
        let mut s = state.unwrap_or(Presence {
            value: SpringValue::new(spring, [if show { 1. } else { 0. }]),
            mounted: show,
        });
        let now = Instant::now();
        if show {
            s.mounted = true;
            s.value = SpringValue::new(spring, [1.]);
            return ((Some(1.), false), s);
        }
        if !s.mounted || settings.reduced {
            s.mounted = false;
            return ((None, false), s);
        }
        if s.value.target != [0.] {
            s.value.update([0.], spring, 0., now);
        }
        let t = now.duration_since(s.value.start).as_secs_f32() / settings.time_scale.max(0.01);
        let ([value], moving) = s.value.update([0.], spring, t, now);
        if !moving || value <= 0.01 {
            s.mounted = false;
            return ((None, false), s);
        }
        ((Some(value.clamp(0., 1.)), true), s)
    });
    if moving {
        request_frame_for(window, &label);
    }
    value
}

struct Presence {
    value: SpringValue<1>,
    mounted: bool,
}

/// What an expanding section should draw this frame. See [`expand`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Expand {
    /// Closed and at rest: draw nothing.
    Hidden,
    /// Open and at rest: draw the content at its natural height (it may keep growing).
    Natural,
    /// Opening or closing: draw the content clipped to this height.
    Clipped(Pixels),
}

struct ExpandState {
    open: bool,
    value: Option<SpringValue<1>>,
}

/// Height animation for content that opens and closes (an expandable card's body).
///
/// `measured` is the content's natural height, measured in the previous frame (0 if unknown).
/// When `open` changes, the height springs between 0 and `measured`; at rest it returns
/// [`Expand::Natural`] or [`Expand::Hidden`], so open content can change size freely. Nothing
/// animates on the first frame (content that starts open is just shown).
#[track_caller]
pub fn expand(
    id: impl Into<ElementId>,
    open: bool,
    measured: Pixels,
    spring: Spring,
    window: &mut Window,
    cx: &mut App,
) -> Expand {
    let settings = MotionSettings::get(cx);
    let measured = f32::from(measured).max(0.);
    let id = id.into();
    let label = frame_label(&id);
    let (result, moving) = element_state(id, window, |state: Option<ExpandState>, _| {
        let mut s = state.unwrap_or(ExpandState { open, value: None });
        let rest = if open {
            Expand::Natural
        } else {
            Expand::Hidden
        };
        if settings.reduced {
            s.open = open;
            s.value = None;
            return ((rest, false), s);
        }
        let now = Instant::now();
        if s.open != open {
            s.open = open;
            if s.value.is_none() {
                let from = if open { 0. } else { measured };
                s.value = Some(SpringValue::new(spring, [from]));
            }
        }
        let Some(value) = s.value.as_mut() else {
            return ((rest, false), s);
        };
        // Opening content that was never measured: lay it out clipped to 0 for one frame.
        if open && measured <= 0. {
            return ((Expand::Clipped(px(0.)), true), s);
        }
        let target = if open { measured } else { 0. };
        let t = now.duration_since(value.start).as_secs_f32() / settings.time_scale.max(0.01);
        let ([h], moving) = value.update([target], spring, t, now);
        if !moving {
            s.value = None;
            return ((rest, false), s);
        }
        ((Expand::Clipped(px(h.max(0.))), true), s)
    });
    if moving {
        request_frame_for(window, &label);
    }
    result
}

/// Axis of a [`Enter::shared_axis`] transition.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum SharedAxis {
    /// Sideways: tabs, steps of a flow (forward comes from the right).
    #[default]
    X,
    /// Up and down: a list that pages, a stepper (forward comes from below).
    Y,
    /// In depth: parent and child (GPUI cannot scale, so it only fades in).
    Z,
}

/// An entrance for any element: it slides in from an offset and fades in with a spring,
/// optionally after a delay (to stagger a list, see [`stagger`]). Approximates M3's enter
/// transitions with offset and opacity (GPUI does not scale elements).
///
/// ```ignore
/// let row = div().child(..);
/// let row = Enter::new(("row-in", i)).delay(stagger(i, 0.03, 6)).apply(row, window, cx);
/// ```
///
/// Its state lives while the element is drawn: shown again after being removed, it enters
/// again. With [`Enter::on_change`] it plays each time a generation changes instead (new
/// content in the same place). Nothing animates with reduced motion, and a finished entrance
/// returns the element untouched and requests no frames.
#[derive(Clone)]
pub struct Enter {
    id: ElementId,
    delay: f32,
    dx: f32,
    dy: f32,
    spring: Spring,
    generation: Option<u64>,
}

impl Enter {
    /// Rises 12 px with the spatial spring. `id` must be unique within the view; a new one
    /// makes the element enter again.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            delay: 0.,
            dx: 0.,
            dy: 12.,
            spring: Spring::SPATIAL,
            generation: None,
        }
    }

    /// The incoming half of an M3 shared axis transition: 30 px along `axis`, from the
    /// leading side when `forward` (right or below) and from the trailing side when going
    /// back. Use it with [`Enter::on_change`] keyed by the page shown.
    pub fn shared_axis(mut self, axis: SharedAxis, forward: bool) -> Self {
        let distance = if forward { 30. } else { -30. };
        (self.dx, self.dy) = match axis {
            SharedAxis::X => (distance, 0.),
            SharedAxis::Y => (0., distance),
            SharedAxis::Z => (0., 0.),
        };
        self
    }

    /// Seconds to wait before starting.
    pub fn delay(mut self, delay: f32) -> Self {
        self.delay = delay.max(0.);
        self
    }

    /// Where it comes from, in pixels (`dx` > 0: from the right; `dy` > 0: from below).
    pub fn from(mut self, dx: f32, dy: f32) -> Self {
        self.dx = dx;
        self.dy = dy;
        self
    }

    pub fn spring(mut self, spring: Spring) -> Self {
        self.spring = spring;
        self
    }

    /// Enters each time `generation` changes instead of when it appears.
    pub fn on_change(mut self, generation: u64) -> Self {
        self.generation = Some(generation);
        self
    }

    /// Progress from 0 to 1 (with the spring's bounce); exactly 1 once finished.
    #[track_caller]
    pub fn progress(self, window: &mut Window, cx: &mut App) -> f32 {
        match self.generation {
            None => entrance(self.id, self.spring, self.delay, window, cx),
            Some(generation) => {
                let duration = self.spring.settle_time().as_secs_f32() + self.delay;
                match replay(self.id, generation, duration, window, cx) {
                    Some(t) => self.spring.step((t - self.delay).max(0.)),
                    None => 1.,
                }
            }
        }
    }

    /// Applies the entrance to `el` (offset and opacity); a finished one returns it untouched.
    #[track_caller]
    pub fn apply<E: Styled>(self, el: E, window: &mut Window, cx: &mut App) -> E {
        let (dx, dy) = (self.dx, self.dy);
        let p = self.progress(window, cx);
        if p == 1. {
            return el;
        }
        el.relative()
            .left(px((1. - p) * dx))
            .top(px((1. - p) * dy))
            .opacity(p.clamp(0., 1.))
    }
}

/// Delay of row `index` of a staggered list: `step` seconds between rows, up to `max` rows so
/// a long list does not take long to finish entering.
pub fn stagger(index: usize, step: f32, max: usize) -> f32 {
    index.min(max) as f32 * step
}

pub fn key(id: &ElementId, name: &'static str) -> ElementId {
    ElementId::NamedChild(Box::new(id.clone()), name.into())
}

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

    #[test]
    fn ticks_land_on_a_shared_grid() {
        let at = |now: f64, fps: f64| now + delay_to_tick(now, fps);
        let on_grid = |t: f64| ((t * 60.) - (t * 60.).round()).abs() < 1e-6;
        // 30 fps: the next multiple of 1/30, always ahead of `now`.
        assert!((at(0.010, 30.) - 1. / 30.).abs() < 1e-9);
        assert!((at(1. / 30., 30.) - 2. / 30.).abs() < 1e-9);
        // A caret at 4 fps and a spinner at 30 fps tick on the same 60 Hz grid.
        assert!((at(0.20, 4.) - 0.25).abs() < 1e-9);
        for i in 0..200 {
            let now = i as f64 * 0.0137;
            assert!(on_grid(at(now, 30.)) && on_grid(at(now, 4.)) && on_grid(at(now, 12.)));
        }
        // A rate that is not on the grid moves forward onto it.
        let t = at(0.0, 24.);
        assert!(t >= 1. / 24. && on_grid(t));
        // Never fires twice on the same tick, never waits more than a period plus a grid step.
        for i in 0..1000 {
            let now = i as f64 * 0.00731;
            let delay = delay_to_tick(now, 30.);
            assert!(delay > 0. && delay <= 1. / 30. + 1. / 60. + 1e-3);
        }
    }

    #[test]
    fn stagger_has_a_cap() {
        assert_eq!(stagger(0, 0.03, 6), 0.);
        assert!((stagger(2, 0.03, 6) - 0.06).abs() < 1e-6);
        assert!((stagger(40, 0.03, 6) - 0.18).abs() < 1e-6);
    }

    #[test]
    fn shared_axis_comes_from_the_leading_side() {
        let enter = |axis, forward| {
            let e = Enter::new("e").shared_axis(axis, forward);
            (e.dx, e.dy)
        };
        assert_eq!(enter(SharedAxis::X, true), (30., 0.));
        assert_eq!(enter(SharedAxis::X, false), (-30., 0.));
        assert_eq!(enter(SharedAxis::Y, true), (0., 30.));
        assert_eq!(enter(SharedAxis::Z, false), (0., 0.));
    }

    #[test]
    fn springs_settle_on_target() {
        for spring in [
            Spring::SPATIAL_FAST,
            Spring::SPATIAL,
            Spring::SPATIAL_SLOW,
            Spring::EFFECTS_FAST,
            Spring::EFFECTS,
            Spring::EFFECTS_SLOW,
        ] {
            let end = spring.step(spring.settle_time().as_secs_f32());
            assert!((end - 1.).abs() < 0.002, "{spring:?} ends at {end}");
        }
    }

    #[test]
    fn spatial_springs_bounce_and_effects_do_not() {
        let peak = |s: Spring| {
            (0..400)
                .map(|i| s.step(i as f32 / 400.))
                .fold(0f32, f32::max)
        };
        // Damping 0.6 overshoots about 9.5%, like the reference CSS curve (1.093).
        assert!((peak(Spring::SPATIAL_FAST) - 1.095).abs() < 0.005);
        assert!(peak(Spring::EFFECTS) <= 1.0001);
    }

    #[test]
    fn retargeting_from_rest_starts_from_the_old_value() {
        let now = Instant::now();
        let mut value = SpringValue::new(Spring::SPATIAL, [120.]);
        let (start, moving) = value.update([0.], Spring::SPATIAL, 0., now);
        assert!(moving);
        assert!((start[0] - 120.).abs() < 1e-4);
        let (later, _) = value.update([0.], Spring::SPATIAL, 0.1, now);
        assert!(later[0] < 120. && later[0] > 0.);
    }

    #[test]
    fn retargeting_keeps_position() {
        let now = Instant::now();
        let mut value = SpringValue::new(Spring::SPATIAL, [0.]);
        value.update([10.], Spring::SPATIAL, 0., now);
        let (mid, _) = value.update([10.], Spring::SPATIAL, 0.1, now);
        // Changing the target mid-flight continues from where the value is, without a jump.
        let (after, moving) = value.update([0.], Spring::SPATIAL, 0.1, now);
        assert!(moving);
        assert!((after[0] - mid[0]).abs() < 1e-4);
    }

    /// Frames `update` asks for (calls that return `moving`) when sampled at 120 fps for
    /// `seconds` toward `target`.
    fn moving_frames(value: &mut SpringValue<1>, target: f32, seconds: f32) -> usize {
        let now = Instant::now();
        (0..(seconds * 120.) as usize)
            .filter(|&i| value.update([target], value.spring, i as f32 / 120., now).1)
            .count()
    }

    #[test]
    fn a_settled_spring_asks_for_no_more_frames() {
        for spring in [Spring::SPATIAL_FAST, Spring::SPATIAL, Spring::EFFECTS] {
            // A hover layer (0 → 1) and a size in pixels (0 → 600 px).
            for target in [1., 600.] {
                let mut value = SpringValue::new(spring, [0.]);
                let busy = moving_frames(&mut value, target, 2.);
                // It moves for a while and then rests within about twice its settle time.
                let limit = (spring.settle_time().as_secs_f32() * 2. * 120.) as usize;
                assert!(busy > 0 && busy < limit, "{spring:?} → {target}: {busy} frames");
                // At rest with the same target: nothing, however late it is drawn again.
                assert_eq!(moving_frames(&mut value, target, 1.), 0);
                let (rest, moving) = value.update([target], spring, 60., Instant::now());
                assert!(!moving && rest == [target]);
            }
        }
    }

    #[test]
    fn entrances_stop_asking_for_frames_once_settled() {
        for spring in [Spring::SPATIAL, Spring::EFFECTS] {
            let settle = spring.settle_time().as_secs_f32();
            // Waiting for its delay: drawn at the start, still asking for frames.
            assert_eq!(entrance_progress(spring, -0.1), Some(0.));
            assert!(entrance_progress(spring, settle * 0.5).is_some());
            // Settled: no frames, at any later time (an event's clock keeps running).
            assert_eq!(entrance_progress(spring, settle), None);
            assert_eq!(entrance_progress(spring, 3600.), None);
        }
    }

    #[test]
    fn a_held_ambient_clock_keeps_its_pose_and_resumes_without_a_jump() {
        let mut clock = Ambient::new(10., true);
        let close = |a: f32, b: f32| (a - b).abs() < 1e-4;
        assert!(close(clock.advance(10.5, true, false), 10.5));
        // Held: the pose stays put while time goes by.
        assert!(close(clock.advance(11., true, true), 10.5));
        assert!(close(clock.advance(40., true, true), 10.5));
        // Resumed: the first frame shows the held pose, then it moves on at the normal pace.
        assert!(close(clock.advance(60., true, false), 10.5));
        assert!(close(clock.advance(60.1, true, false), 10.6));
        // In the background it does not move either.
        assert!(close(clock.advance(61., false, false), 10.6));
    }
}