1use std::{
11 cell::RefCell,
12 collections::{HashMap, HashSet},
13 time::{Duration, Instant},
14};
15
16use gpui::{App, ElementId, EntityId, Global, Hsla, Pixels, Rgba, Styled, Window, WindowId, px};
17
18#[derive(Clone, Copy, Debug, PartialEq)]
20pub struct Spring {
21 pub stiffness: f32,
22 pub damping_ratio: f32,
23}
24
25impl Spring {
26 pub const SPATIAL_FAST: Spring = Spring {
27 stiffness: 800.,
28 damping_ratio: 0.6,
29 };
30 pub const SPATIAL: Spring = Spring {
31 stiffness: 380.,
32 damping_ratio: 0.8,
33 };
34 pub const SPATIAL_SLOW: Spring = Spring {
35 stiffness: 200.,
36 damping_ratio: 0.8,
37 };
38 pub const EFFECTS_FAST: Spring = Spring {
39 stiffness: 3800.,
40 damping_ratio: 1.,
41 };
42 pub const EFFECTS: Spring = Spring {
43 stiffness: 1600.,
44 damping_ratio: 1.,
45 };
46 pub const EFFECTS_SLOW: Spring = Spring {
47 stiffness: 800.,
48 damping_ratio: 1.,
49 };
50
51 pub fn solve(self, x0: f32, v0: f32, t: f32) -> (f32, f32) {
53 let w0 = self.stiffness.sqrt();
54 let z = self.damping_ratio;
55 if z < 1. {
56 let wd = w0 * (1. - z * z).sqrt();
57 let decay = (-z * w0 * t).exp();
58 let a = x0;
59 let b = (v0 + z * w0 * x0) / wd;
60 let (sin, cos) = (wd * t).sin_cos();
61 let x = decay * (a * cos + b * sin);
62 let v = decay * ((b * wd - z * w0 * a) * cos - (a * wd + z * w0 * b) * sin);
63 (x, v)
64 } else {
65 let decay = (-w0 * t).exp();
66 let b = v0 + w0 * x0;
67 ((x0 + b * t) * decay, (v0 - w0 * b * t) * decay)
68 }
69 }
70
71 pub fn step(self, t: f32) -> f32 {
73 1. - self.solve(1., 0., t).0
74 }
75
76 pub fn settle_time(self) -> Duration {
78 let w0 = self.stiffness.sqrt();
79 let z = self.damping_ratio;
80 let seconds = if z < 1. {
81 (1000. / (1. - z * z).sqrt()).ln() / (z * w0)
83 } else {
84 9.25 / w0
86 };
87 Duration::from_secs_f32(seconds)
88 }
89}
90
91#[derive(Clone, Copy, Debug)]
93pub struct MotionSettings {
94 pub time_scale: f32,
95 pub reduced: bool,
96}
97
98impl Default for MotionSettings {
99 fn default() -> Self {
100 Self {
101 time_scale: 1.,
102 reduced: false,
103 }
104 }
105}
106
107impl Global for MotionSettings {}
108
109impl MotionSettings {
110 pub fn get(cx: &App) -> MotionSettings {
111 cx.try_global::<MotionSettings>()
112 .copied()
113 .unwrap_or_default()
114 }
115
116 pub fn sync(reduced: bool, cx: &mut App) -> bool {
120 let current = Self::get(cx);
121 if current.reduced == reduced && cx.has_global::<MotionSettings>() {
122 return false;
123 }
124 cx.set_global(MotionSettings {
125 reduced,
126 ..current
127 });
128 cx.refresh_windows();
129 true
130 }
131}
132
133pub fn elapsed(start: Instant, cx: &App) -> f32 {
135 start.elapsed().as_secs_f32() / MotionSettings::get(cx).time_scale.max(0.01)
136}
137
138pub fn clock(cx: &App) -> f32 {
140 static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
141 elapsed(*START.get_or_init(Instant::now), cx)
142}
143
144#[cfg(feature = "frame-stats")]
148static FRAME_REQUESTS: std::sync::Mutex<Vec<(&'static std::panic::Location<'static>, u32)>> =
149 std::sync::Mutex::new(Vec::new());
150
151#[track_caller]
152pub(crate) fn request_frame(window: &mut Window) {
153 count_frame_request();
154 window.request_animation_frame();
155}
156
157#[track_caller]
161pub fn request_animation_frame(window: &mut Window) {
162 request_frame(window);
163}
164
165#[track_caller]
169pub(crate) fn request_frame_for(window: &mut Window, label: &FrameLabel) {
170 #[cfg(feature = "frame-stats")]
171 note_frame_id(std::panic::Location::caller(), label);
172 #[cfg(not(feature = "frame-stats"))]
173 let _ = label;
174 request_frame(window);
175}
176
177#[cfg(feature = "frame-stats")]
180pub(crate) type FrameLabel = ElementId;
181#[cfg(not(feature = "frame-stats"))]
182pub(crate) type FrameLabel = ();
183
184pub(crate) fn frame_label(id: &ElementId) -> FrameLabel {
185 #[cfg(feature = "frame-stats")]
186 {
187 id.clone()
188 }
189 #[cfg(not(feature = "frame-stats"))]
190 {
191 let _ = id;
192 }
193}
194
195#[cfg(feature = "frame-stats")]
197const FRAME_IDS_MAX: usize = 16;
198
199#[cfg(feature = "frame-stats")]
200type FrameIds = Vec<(&'static std::panic::Location<'static>, Vec<(ElementId, u32)>)>;
201
202#[cfg(feature = "frame-stats")]
203thread_local! {
204 static FRAME_IDS: RefCell<FrameIds> = const { RefCell::new(Vec::new()) };
206}
207
208#[cfg(feature = "frame-stats")]
209fn note_frame_id(at: &'static std::panic::Location<'static>, id: &ElementId) {
210 FRAME_IDS.with(|sites| {
211 let mut sites = sites.borrow_mut();
212 let ids = match sites.iter_mut().position(|(loc, _)| std::ptr::eq(*loc, at)) {
213 Some(i) => &mut sites[i].1,
214 None => {
215 sites.push((at, Vec::new()));
216 &mut sites.last_mut().expect("just pushed").1
217 }
218 };
219 if let Some((_, n)) = ids.iter_mut().find(|(seen, _)| seen == id) {
220 *n += 1;
221 } else if ids.len() < FRAME_IDS_MAX {
222 ids.push((id.clone(), 1));
223 }
224 });
225}
226
227#[track_caller]
231fn count_frame_request() {
232 #[cfg(feature = "frame-stats")]
233 {
234 let at = std::panic::Location::caller();
235 if let Ok(mut list) = FRAME_REQUESTS.lock() {
236 match list.iter_mut().find(|(loc, _)| std::ptr::eq(*loc, at)) {
237 Some((_, n)) => *n += 1,
238 None => list.push((at, 1)),
239 }
240 }
241 }
242}
243
244const TICK_GRID: f64 = 60.;
249
250fn tick_origin() -> Instant {
252 static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
253 *START.get_or_init(Instant::now)
254}
255
256pub fn tick_delay(fps: f32) -> Duration {
260 let now = tick_origin().elapsed().as_secs_f64();
261 Duration::from_secs_f64(delay_to_tick(now, fps as f64))
262}
263
264fn delay_to_tick(now: f64, fps: f64) -> f64 {
268 let period = 1. / fps.clamp(0.1, TICK_GRID);
269 let mut next = ((now / period).floor() + 1.) * period;
270 if next - now < 1e-4 {
271 next += period;
273 }
274 let next = ((next * TICK_GRID) - 1e-6).ceil() / TICK_GRID;
277 (next - now).max(1e-4)
278}
279
280pub fn take_frame_requests() -> Vec<(String, u32)> {
285 #[cfg(feature = "frame-stats")]
286 {
287 let Ok(mut list) = FRAME_REQUESTS.lock() else {
288 return Vec::new();
289 };
290 let ids = FRAME_IDS.with(|sites| std::mem::take(&mut *sites.borrow_mut()));
291 let mut out: Vec<(String, u32)> = list
292 .drain(..)
293 .map(|(at, n)| {
294 let top = ids
295 .iter()
296 .find(|(loc, _)| std::ptr::eq(*loc, at))
297 .and_then(|(_, ids)| ids.iter().max_by_key(|(_, n)| *n));
298 let site = match top {
299 Some((id, k)) => format!("{}:{} [{id} ×{k}]", at.file(), at.line()),
300 None => format!("{}:{}", at.file(), at.line()),
301 };
302 (site, n)
303 })
304 .collect();
305 out.sort_by_key(|entry| std::cmp::Reverse(entry.1));
306 out
307 }
308 #[cfg(not(feature = "frame-stats"))]
309 Vec::new()
310}
311
312#[track_caller]
315pub fn continuous(window: &mut Window, cx: &App) -> f32 {
316 if MotionSettings::get(cx).reduced {
317 return 0.;
318 }
319 request_frame(window);
320 clock(cx)
321}
322
323const BACKGROUND_FPS: f32 = 4.;
325
326thread_local! {
327 static PENDING: RefCell<HashSet<EntityId>> = RefCell::new(HashSet::new());
329 static AMBIENT: RefCell<HashMap<WindowId, Ambient>> = RefCell::new(HashMap::new());
331}
332
333struct Ambient {
334 real: f32,
335 shown: f32,
336 active: bool,
337 held: bool,
338}
339
340impl Ambient {
341 fn new(now: f32, active: bool) -> Self {
342 Ambient {
343 real: now,
344 shown: now,
345 active,
346 held: false,
347 }
348 }
349
350 fn advance(&mut self, now: f32, active: bool, held: bool) -> f32 {
354 if active && self.active && !held && !self.held {
356 self.shown += (now - self.real).clamp(0., 0.5);
357 }
358 self.real = now;
359 self.active = active;
360 self.held = held;
361 self.shown
362 }
363}
364
365pub fn ambient_clock(window: &Window, cx: &App) -> f32 {
369 ambient_tick(window, cx, false)
370}
371
372pub(crate) fn held_ambient_clock(window: &Window, cx: &App) -> f32 {
375 ambient_tick(window, cx, true)
376}
377
378fn ambient_tick(window: &Window, cx: &App, held: bool) -> f32 {
379 if MotionSettings::get(cx).reduced {
380 return 0.;
381 }
382 let now = clock(cx);
383 let active = window.is_window_active();
384 AMBIENT.with(|map| {
385 map.borrow_mut()
386 .entry(window.window_handle().window_id())
387 .or_insert_with(|| Ambient::new(now, active))
388 .advance(now, active, held)
389 })
390}
391
392#[track_caller]
395pub fn continuous_at(fps: f32, window: &mut Window, cx: &mut App) -> f32 {
396 if MotionSettings::get(cx).reduced {
397 return 0.;
398 }
399 let fps = if window.is_window_active() {
402 fps
403 } else {
404 fps.min(BACKGROUND_FPS)
405 };
406 if fps >= 60. {
407 request_frame(window);
408 return clock(cx);
409 }
410 let view = window.current_view();
411 if PENDING.with(|p| p.borrow_mut().insert(view)) {
412 count_frame_request();
413 let timer = cx.background_executor().timer(tick_delay(fps.max(1.)));
415 cx.spawn(async move |cx| {
416 timer.await;
417 PENDING.with(|p| p.borrow_mut().remove(&view));
418 cx.update(|cx| cx.notify(view)).ok();
419 })
420 .detach();
421 }
422 clock(cx)
423}
424
425#[derive(Clone, Debug)]
427pub struct SpringValue<const N: usize> {
428 spring: Spring,
429 target: [f32; N],
430 offset: [f32; N],
431 velocity: [f32; N],
432 start: Instant,
433 settled: bool,
434}
435
436impl<const N: usize> SpringValue<N> {
437 pub fn new(spring: Spring, value: [f32; N]) -> Self {
438 Self {
439 spring,
440 target: value,
441 offset: [0.; N],
442 velocity: [0.; N],
443 start: Instant::now(),
444 settled: true,
445 }
446 }
447
448 fn sample(&self, t: f32) -> ([f32; N], [f32; N]) {
450 let mut value = self.target;
451 let mut velocity = [0.; N];
452 if !self.settled {
453 for i in 0..N {
454 let (x, v) = self.spring.solve(self.offset[i], self.velocity[i], t);
455 value[i] = self.target[i] + x;
456 velocity[i] = v;
457 }
458 }
459 (value, velocity)
460 }
461
462 pub fn update(
464 &mut self,
465 target: [f32; N],
466 spring: Spring,
467 t: f32,
468 now: Instant,
469 ) -> ([f32; N], bool) {
470 if target != self.target || spring != self.spring {
471 let (value, velocity) = self.sample(t);
472 for i in 0..N {
473 self.offset[i] = value[i] - target[i];
474 self.velocity[i] = velocity[i];
475 }
476 self.target = target;
477 self.spring = spring;
478 self.start = now;
479 self.settled = false;
480 return (value, true);
481 }
482 if self.settled {
483 return (self.target, false);
484 }
485 let (value, velocity) = self.sample(t);
486 let resting =
487 (0..N).all(|i| (value[i] - self.target[i]).abs() < 0.002 && velocity[i].abs() < 0.05);
488 if resting {
489 self.settled = true;
490 return (self.target, false);
491 }
492 (value, true)
493 }
494
495 pub fn kick(&mut self, from: [f32; N], now: Instant) {
497 for (offset, (from, target)) in self.offset.iter_mut().zip(from.iter().zip(&self.target)) {
498 *offset = from - target;
499 }
500 self.velocity = [0.; N];
501 self.start = now;
502 self.settled = false;
503 }
504}
505
506#[track_caller]
511pub fn animate<const N: usize>(
512 id: impl Into<ElementId>,
513 spring: Spring,
514 target: [f32; N],
515 window: &mut Window,
516 cx: &mut App,
517) -> [f32; N] {
518 animate_inner(id.into(), spring, target, None, window, cx)
519}
520
521#[track_caller]
523pub fn animate_from<const N: usize>(
524 id: impl Into<ElementId>,
525 spring: Spring,
526 from: [f32; N],
527 target: [f32; N],
528 window: &mut Window,
529 cx: &mut App,
530) -> [f32; N] {
531 animate_inner(id.into(), spring, target, Some(from), window, cx)
532}
533
534#[track_caller]
535fn animate_inner<const N: usize>(
536 id: ElementId,
537 spring: Spring,
538 target: [f32; N],
539 from: Option<[f32; N]>,
540 window: &mut Window,
541 cx: &mut App,
542) -> [f32; N] {
543 let settings = MotionSettings::get(cx);
544 let label = frame_label(&id);
545 let (value, moving) = element_state(id, window, |state: Option<SpringValue<N>>, _| {
546 let mut s = state.unwrap_or_else(|| {
547 let mut value = SpringValue::new(spring, target);
548 if let Some(from) = from {
549 value.kick(from, Instant::now());
550 }
551 value
552 });
553 if settings.reduced {
554 return ((target, false), SpringValue::new(spring, target));
555 }
556 if s.settled && s.target == target && s.spring == spring {
558 return ((target, false), s);
559 }
560 let now = Instant::now();
561 let t = now.duration_since(s.start).as_secs_f32() / settings.time_scale.max(0.01);
562 #[cfg(feature = "frame-stats")]
565 if (target != s.target || spring != s.spring) && t < 0.004 {
566 log::warn!("spring {label:?} retargeted twice within a frame (duplicate element id)");
567 }
568 (s.update(target, spring, t, now), s)
569 });
570 if moving {
571 request_frame_for(window, &label);
572 }
573 value
574}
575
576pub(crate) fn element_state<S: 'static, R>(
579 id: ElementId,
580 window: &mut Window,
581 f: impl FnOnce(Option<S>, &mut Window) -> (R, S),
582) -> R {
583 window.with_global_id(id, |global_id, window| {
584 window.with_element_state(global_id, f)
585 })
586}
587
588struct Triggered<const N: usize> {
589 value: SpringValue<N>,
590 active: bool,
591}
592
593#[track_caller]
596pub fn animate_on_activate<const N: usize>(
597 id: impl Into<ElementId>,
598 spring: Spring,
599 active: bool,
600 from: [f32; N],
601 rest: [f32; N],
602 window: &mut Window,
603 cx: &mut App,
604) -> [f32; N] {
605 let settings = MotionSettings::get(cx);
606 let id = id.into();
607 let label = frame_label(&id);
608 let (value, moving) = element_state(id, window, |state: Option<Triggered<N>>, _| {
609 let mut s = state.unwrap_or_else(|| {
610 let mut value = SpringValue::new(spring, rest);
611 if active {
613 value.kick(from, Instant::now());
614 }
615 Triggered { value, active }
616 });
617 if settings.reduced {
618 return ((rest, false), s);
619 }
620 let now = Instant::now();
621 if active && !s.active {
622 s.value.kick(from, now);
623 }
624 s.active = active;
625 if s.value.settled && s.value.target == rest {
626 return ((rest, false), s);
627 }
628 let t = now.duration_since(s.value.start).as_secs_f32() / settings.time_scale.max(0.01);
629 (s.value.update(rest, spring, t, now), s)
630 });
631 if moving {
632 request_frame_for(window, &label);
633 }
634 value
635}
636
637#[track_caller]
640pub fn entrance(
641 id: impl Into<ElementId>,
642 spring: Spring,
643 delay: f32,
644 window: &mut Window,
645 cx: &mut App,
646) -> f32 {
647 let settings = MotionSettings::get(cx);
648 let id = id.into();
649 let label = frame_label(&id);
650 let start = element_state(id, window, |start: Option<Instant>, _| {
651 let start = start.unwrap_or_else(Instant::now);
652 (start, start)
653 });
654 if settings.reduced {
655 return 1.;
656 }
657 match entrance_progress(spring, elapsed(start, cx) - delay) {
658 Some(p) => {
659 request_frame_for(window, &label);
660 p
661 }
662 None => 1.,
663 }
664}
665
666#[track_caller]
672pub fn entrance_since(
673 start: Instant,
674 spring: Spring,
675 delay: f32,
676 window: &mut Window,
677 cx: &App,
678) -> f32 {
679 if MotionSettings::get(cx).reduced {
680 return 1.;
681 }
682 match entrance_progress(spring, elapsed(start, cx) - delay) {
683 Some(p) => {
684 request_frame(window);
685 p
686 }
687 None => 1.,
688 }
689}
690
691fn entrance_progress(spring: Spring, t: f32) -> Option<f32> {
694 (t < spring.settle_time().as_secs_f32()).then(|| spring.step(t.max(0.)))
695}
696
697#[track_caller]
699pub fn animate_f32(
700 id: impl Into<ElementId>,
701 spring: Spring,
702 target: f32,
703 window: &mut Window,
704 cx: &mut App,
705) -> f32 {
706 animate(id, spring, [target], window, cx)[0]
707}
708
709#[track_caller]
711pub fn animate_px(
712 id: impl Into<ElementId>,
713 spring: Spring,
714 target: Pixels,
715 window: &mut Window,
716 cx: &mut App,
717) -> Pixels {
718 px(animate(id, spring, [f32::from(target)], window, cx)[0])
719}
720
721#[track_caller]
723pub fn animate_color(
724 id: impl Into<ElementId>,
725 spring: Spring,
726 target: Hsla,
727 window: &mut Window,
728 cx: &mut App,
729) -> Hsla {
730 let c = Rgba::from(target);
731 let [r, g, b, a] = animate(id, spring, [c.r, c.g, c.b, c.a], window, cx);
732 Rgba {
733 r: r.clamp(0., 1.),
734 g: g.clamp(0., 1.),
735 b: b.clamp(0., 1.),
736 a: a.clamp(0., 1.),
737 }
738 .into()
739}
740
741pub fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32) -> impl Fn(f32) -> f32 + Copy {
743 move |x: f32| {
744 if x <= 0. {
745 return 0.;
746 }
747 if x >= 1. {
748 return 1.;
749 }
750 let bez = |t: f32, a: f32, b: f32| {
751 3. * a * t * (1. - t).powi(2) + 3. * b * t * t * (1. - t) + t.powi(3)
752 };
753 let (mut lo, mut hi) = (0f32, 1f32);
754 let mut t = x;
755 for _ in 0..24 {
756 let v = bez(t, x1, x2);
757 if (v - x).abs() < 1e-5 {
758 break;
759 }
760 if v < x {
761 lo = t;
762 } else {
763 hi = t;
764 }
765 t = (lo + hi) / 2.;
766 }
767 bez(t, y1, y2)
768 }
769}
770
771#[track_caller]
775pub fn pulse(period: f32, window: &mut Window, cx: &mut App) -> f32 {
776 if MotionSettings::get(cx).reduced {
777 return 1.;
778 }
779 let t = continuous_at(30., window, cx);
780 0.725 + 0.275 * (t / period.max(0.1) * std::f32::consts::TAU).cos()
781}
782
783#[track_caller]
787pub fn replay(
788 id: impl Into<ElementId>,
789 generation: u64,
790 duration: f32,
791 window: &mut Window,
792 cx: &mut App,
793) -> Option<f32> {
794 let settings = MotionSettings::get(cx);
795 let id = id.into();
796 let label = frame_label(&id);
797 let start = element_state(
798 id,
799 window,
800 |state: Option<(u64, Option<Instant>)>, _| {
801 let state = match state {
802 Some((g, start)) if g == generation => (g, start),
803 Some(_) => (generation, Some(Instant::now())),
804 None => (generation, None),
805 };
806 (state.1, state)
807 },
808 );
809 if settings.reduced {
810 return None;
811 }
812 let t = elapsed(start?, cx);
813 (t < duration).then(|| {
814 request_frame_for(window, &label);
815 t
816 })
817}
818
819#[track_caller]
823pub fn play_on_rise(
824 id: impl Into<ElementId>,
825 active: bool,
826 duration: f32,
827 window: &mut Window,
828 cx: &mut App,
829) -> Option<f32> {
830 let settings = MotionSettings::get(cx);
831 let id = id.into();
832 let label = frame_label(&id);
833 let start = element_state(
834 id,
835 window,
836 |state: Option<(bool, Option<Instant>)>, _| {
837 let state = match state {
838 Some((false, _)) if active => (true, Some(Instant::now())),
839 Some((_, start)) => (active, start),
840 None => (active, None),
841 };
842 (state.1, state)
843 },
844 );
845 if settings.reduced {
846 return None;
847 }
848 let t = elapsed(start?, cx);
849 (t < duration).then(|| {
850 request_frame_for(window, &label);
851 t
852 })
853}
854
855#[track_caller]
870pub fn presence(
871 id: impl Into<ElementId>,
872 show: bool,
873 window: &mut Window,
874 cx: &mut App,
875) -> Option<f32> {
876 let settings = MotionSettings::get(cx);
877 let spring = Spring::EFFECTS_FAST;
878 let id = id.into();
879 let label = frame_label(&id);
880 let (value, moving) = element_state(id, window, |state: Option<Presence>, _| {
881 let mut s = state.unwrap_or(Presence {
882 value: SpringValue::new(spring, [if show { 1. } else { 0. }]),
883 mounted: show,
884 });
885 let now = Instant::now();
886 if show {
887 s.mounted = true;
888 s.value = SpringValue::new(spring, [1.]);
889 return ((Some(1.), false), s);
890 }
891 if !s.mounted || settings.reduced {
892 s.mounted = false;
893 return ((None, false), s);
894 }
895 if s.value.target != [0.] {
896 s.value.update([0.], spring, 0., now);
897 }
898 let t = now.duration_since(s.value.start).as_secs_f32() / settings.time_scale.max(0.01);
899 let ([value], moving) = s.value.update([0.], spring, t, now);
900 if !moving || value <= 0.01 {
901 s.mounted = false;
902 return ((None, false), s);
903 }
904 ((Some(value.clamp(0., 1.)), true), s)
905 });
906 if moving {
907 request_frame_for(window, &label);
908 }
909 value
910}
911
912struct Presence {
913 value: SpringValue<1>,
914 mounted: bool,
915}
916
917#[derive(Clone, Copy, Debug, PartialEq)]
919pub enum Expand {
920 Hidden,
922 Natural,
924 Clipped(Pixels),
926}
927
928struct ExpandState {
929 open: bool,
930 value: Option<SpringValue<1>>,
931}
932
933#[track_caller]
940pub fn expand(
941 id: impl Into<ElementId>,
942 open: bool,
943 measured: Pixels,
944 spring: Spring,
945 window: &mut Window,
946 cx: &mut App,
947) -> Expand {
948 let settings = MotionSettings::get(cx);
949 let measured = f32::from(measured).max(0.);
950 let id = id.into();
951 let label = frame_label(&id);
952 let (result, moving) = element_state(id, window, |state: Option<ExpandState>, _| {
953 let mut s = state.unwrap_or(ExpandState { open, value: None });
954 let rest = if open {
955 Expand::Natural
956 } else {
957 Expand::Hidden
958 };
959 if settings.reduced {
960 s.open = open;
961 s.value = None;
962 return ((rest, false), s);
963 }
964 let now = Instant::now();
965 if s.open != open {
966 s.open = open;
967 if s.value.is_none() {
968 let from = if open { 0. } else { measured };
969 s.value = Some(SpringValue::new(spring, [from]));
970 }
971 }
972 let Some(value) = s.value.as_mut() else {
973 return ((rest, false), s);
974 };
975 if open && measured <= 0. {
977 return ((Expand::Clipped(px(0.)), true), s);
978 }
979 let target = if open { measured } else { 0. };
980 let t = now.duration_since(value.start).as_secs_f32() / settings.time_scale.max(0.01);
981 let ([h], moving) = value.update([target], spring, t, now);
982 if !moving {
983 s.value = None;
984 return ((rest, false), s);
985 }
986 ((Expand::Clipped(px(h.max(0.))), true), s)
987 });
988 if moving {
989 request_frame_for(window, &label);
990 }
991 result
992}
993
994#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
996#[non_exhaustive]
997pub enum SharedAxis {
998 #[default]
1000 X,
1001 Y,
1003 Z,
1005}
1006
1007#[derive(Clone)]
1021pub struct Enter {
1022 id: ElementId,
1023 delay: f32,
1024 dx: f32,
1025 dy: f32,
1026 spring: Spring,
1027 generation: Option<u64>,
1028}
1029
1030impl Enter {
1031 pub fn new(id: impl Into<ElementId>) -> Self {
1034 Self {
1035 id: id.into(),
1036 delay: 0.,
1037 dx: 0.,
1038 dy: 12.,
1039 spring: Spring::SPATIAL,
1040 generation: None,
1041 }
1042 }
1043
1044 pub fn shared_axis(mut self, axis: SharedAxis, forward: bool) -> Self {
1048 let distance = if forward { 30. } else { -30. };
1049 (self.dx, self.dy) = match axis {
1050 SharedAxis::X => (distance, 0.),
1051 SharedAxis::Y => (0., distance),
1052 SharedAxis::Z => (0., 0.),
1053 };
1054 self
1055 }
1056
1057 pub fn delay(mut self, delay: f32) -> Self {
1059 self.delay = delay.max(0.);
1060 self
1061 }
1062
1063 pub fn from(mut self, dx: f32, dy: f32) -> Self {
1065 self.dx = dx;
1066 self.dy = dy;
1067 self
1068 }
1069
1070 pub fn spring(mut self, spring: Spring) -> Self {
1071 self.spring = spring;
1072 self
1073 }
1074
1075 pub fn on_change(mut self, generation: u64) -> Self {
1077 self.generation = Some(generation);
1078 self
1079 }
1080
1081 #[track_caller]
1083 pub fn progress(self, window: &mut Window, cx: &mut App) -> f32 {
1084 match self.generation {
1085 None => entrance(self.id, self.spring, self.delay, window, cx),
1086 Some(generation) => {
1087 let duration = self.spring.settle_time().as_secs_f32() + self.delay;
1088 match replay(self.id, generation, duration, window, cx) {
1089 Some(t) => self.spring.step((t - self.delay).max(0.)),
1090 None => 1.,
1091 }
1092 }
1093 }
1094 }
1095
1096 #[track_caller]
1098 pub fn apply<E: Styled>(self, el: E, window: &mut Window, cx: &mut App) -> E {
1099 let (dx, dy) = (self.dx, self.dy);
1100 let p = self.progress(window, cx);
1101 if p == 1. {
1102 return el;
1103 }
1104 el.relative()
1105 .left(px((1. - p) * dx))
1106 .top(px((1. - p) * dy))
1107 .opacity(p.clamp(0., 1.))
1108 }
1109}
1110
1111pub fn stagger(index: usize, step: f32, max: usize) -> f32 {
1114 index.min(max) as f32 * step
1115}
1116
1117pub fn key(id: &ElementId, name: &'static str) -> ElementId {
1118 ElementId::NamedChild(Box::new(id.clone()), name.into())
1119}
1120
1121#[cfg(test)]
1122mod tests {
1123 use super::*;
1124
1125 #[test]
1126 fn ticks_land_on_a_shared_grid() {
1127 let at = |now: f64, fps: f64| now + delay_to_tick(now, fps);
1128 let on_grid = |t: f64| ((t * 60.) - (t * 60.).round()).abs() < 1e-6;
1129 assert!((at(0.010, 30.) - 1. / 30.).abs() < 1e-9);
1131 assert!((at(1. / 30., 30.) - 2. / 30.).abs() < 1e-9);
1132 assert!((at(0.20, 4.) - 0.25).abs() < 1e-9);
1134 for i in 0..200 {
1135 let now = i as f64 * 0.0137;
1136 assert!(on_grid(at(now, 30.)) && on_grid(at(now, 4.)) && on_grid(at(now, 12.)));
1137 }
1138 let t = at(0.0, 24.);
1140 assert!(t >= 1. / 24. && on_grid(t));
1141 for i in 0..1000 {
1143 let now = i as f64 * 0.00731;
1144 let delay = delay_to_tick(now, 30.);
1145 assert!(delay > 0. && delay <= 1. / 30. + 1. / 60. + 1e-3);
1146 }
1147 }
1148
1149 #[test]
1150 fn stagger_has_a_cap() {
1151 assert_eq!(stagger(0, 0.03, 6), 0.);
1152 assert!((stagger(2, 0.03, 6) - 0.06).abs() < 1e-6);
1153 assert!((stagger(40, 0.03, 6) - 0.18).abs() < 1e-6);
1154 }
1155
1156 #[test]
1157 fn shared_axis_comes_from_the_leading_side() {
1158 let enter = |axis, forward| {
1159 let e = Enter::new("e").shared_axis(axis, forward);
1160 (e.dx, e.dy)
1161 };
1162 assert_eq!(enter(SharedAxis::X, true), (30., 0.));
1163 assert_eq!(enter(SharedAxis::X, false), (-30., 0.));
1164 assert_eq!(enter(SharedAxis::Y, true), (0., 30.));
1165 assert_eq!(enter(SharedAxis::Z, false), (0., 0.));
1166 }
1167
1168 #[test]
1169 fn springs_settle_on_target() {
1170 for spring in [
1171 Spring::SPATIAL_FAST,
1172 Spring::SPATIAL,
1173 Spring::SPATIAL_SLOW,
1174 Spring::EFFECTS_FAST,
1175 Spring::EFFECTS,
1176 Spring::EFFECTS_SLOW,
1177 ] {
1178 let end = spring.step(spring.settle_time().as_secs_f32());
1179 assert!((end - 1.).abs() < 0.002, "{spring:?} ends at {end}");
1180 }
1181 }
1182
1183 #[test]
1184 fn spatial_springs_bounce_and_effects_do_not() {
1185 let peak = |s: Spring| {
1186 (0..400)
1187 .map(|i| s.step(i as f32 / 400.))
1188 .fold(0f32, f32::max)
1189 };
1190 assert!((peak(Spring::SPATIAL_FAST) - 1.095).abs() < 0.005);
1192 assert!(peak(Spring::EFFECTS) <= 1.0001);
1193 }
1194
1195 #[test]
1196 fn retargeting_from_rest_starts_from_the_old_value() {
1197 let now = Instant::now();
1198 let mut value = SpringValue::new(Spring::SPATIAL, [120.]);
1199 let (start, moving) = value.update([0.], Spring::SPATIAL, 0., now);
1200 assert!(moving);
1201 assert!((start[0] - 120.).abs() < 1e-4);
1202 let (later, _) = value.update([0.], Spring::SPATIAL, 0.1, now);
1203 assert!(later[0] < 120. && later[0] > 0.);
1204 }
1205
1206 #[test]
1207 fn retargeting_keeps_position() {
1208 let now = Instant::now();
1209 let mut value = SpringValue::new(Spring::SPATIAL, [0.]);
1210 value.update([10.], Spring::SPATIAL, 0., now);
1211 let (mid, _) = value.update([10.], Spring::SPATIAL, 0.1, now);
1212 let (after, moving) = value.update([0.], Spring::SPATIAL, 0.1, now);
1214 assert!(moving);
1215 assert!((after[0] - mid[0]).abs() < 1e-4);
1216 }
1217
1218 fn moving_frames(value: &mut SpringValue<1>, target: f32, seconds: f32) -> usize {
1221 let now = Instant::now();
1222 (0..(seconds * 120.) as usize)
1223 .filter(|&i| value.update([target], value.spring, i as f32 / 120., now).1)
1224 .count()
1225 }
1226
1227 #[test]
1228 fn a_settled_spring_asks_for_no_more_frames() {
1229 for spring in [Spring::SPATIAL_FAST, Spring::SPATIAL, Spring::EFFECTS] {
1230 for target in [1., 600.] {
1232 let mut value = SpringValue::new(spring, [0.]);
1233 let busy = moving_frames(&mut value, target, 2.);
1234 let limit = (spring.settle_time().as_secs_f32() * 2. * 120.) as usize;
1236 assert!(busy > 0 && busy < limit, "{spring:?} → {target}: {busy} frames");
1237 assert_eq!(moving_frames(&mut value, target, 1.), 0);
1239 let (rest, moving) = value.update([target], spring, 60., Instant::now());
1240 assert!(!moving && rest == [target]);
1241 }
1242 }
1243 }
1244
1245 #[test]
1246 fn entrances_stop_asking_for_frames_once_settled() {
1247 for spring in [Spring::SPATIAL, Spring::EFFECTS] {
1248 let settle = spring.settle_time().as_secs_f32();
1249 assert_eq!(entrance_progress(spring, -0.1), Some(0.));
1251 assert!(entrance_progress(spring, settle * 0.5).is_some());
1252 assert_eq!(entrance_progress(spring, settle), None);
1254 assert_eq!(entrance_progress(spring, 3600.), None);
1255 }
1256 }
1257
1258 #[test]
1259 fn a_held_ambient_clock_keeps_its_pose_and_resumes_without_a_jump() {
1260 let mut clock = Ambient::new(10., true);
1261 let close = |a: f32, b: f32| (a - b).abs() < 1e-4;
1262 assert!(close(clock.advance(10.5, true, false), 10.5));
1263 assert!(close(clock.advance(11., true, true), 10.5));
1265 assert!(close(clock.advance(40., true, true), 10.5));
1266 assert!(close(clock.advance(60., true, false), 10.5));
1268 assert!(close(clock.advance(60.1, true, false), 10.6));
1269 assert!(close(clock.advance(61., false, false), 10.6));
1271 }
1272}