Skip to main content

gpui_m3/
motion.rs

1//! M3 Expressive motion: physics-based springs (not fixed-duration curves).
2//!
3//! The values are the official ones from `androidx.compose.material3` (`MotionScheme.expressive()`):
4//! spatial springs for position, size and shape (with bounce) and effects springs for color and opacity (no bounce).
5//! When the target changes mid-flight the spring keeps its velocity, as in Compose.
6//!
7//! GPUI does not support curves that overshoot 1 in `with_animation`, so components
8//! animate with [`animate`], which keeps the spring state between frames.
9
10use 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/// Unit-mass spring: stiffness and damping ratio.
19#[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    /// Displacement and velocity after `t` seconds, starting from `x0` (relative to the target) with velocity `v0`.
52    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    /// Step response (0 → 1) after `t` seconds. May exceed 1 (bounce).
72    pub fn step(self, t: f32) -> f32 {
73        1. - self.solve(1., 0., t).0
74    }
75
76    /// Approximate time to settle (step response within 0.1 %).
77    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            // The oscillation envelope starts at 1/sqrt(1 - z²), not at 1.
82            (1000. / (1. - z * z).sqrt()).ln() / (z * w0)
83        } else {
84            // Critically damped: (1 + w0·t)·e^(-w0·t) drops below 0.1% at w0·t ≈ 9.23.
85            9.25 / w0
86        };
87        Duration::from_secs_f32(seconds)
88    }
89}
90
91/// Global motion settings. `time_scale` > 1 slows everything down (useful for reviewing animations).
92#[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    /// Follows the system's reduced motion setting: stores `reduced` and redraws every window,
117    /// but only when it changed (call it when a window activates, not every frame). Returns
118    /// whether it changed.
119    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
133/// Seconds elapsed since `start`, in animation time (applying `time_scale`).
134pub fn elapsed(start: Instant, cx: &App) -> f32 {
135    start.elapsed().as_secs_f32() / MotionSettings::get(cx).time_scale.max(0.01)
136}
137
138/// Shared clock for continuous animations (loading indicators, breathing shapes).
139pub 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/// Who asks for frames: each call site of the motion helpers that keeps the window animating,
145/// counted until [`take_frame_requests`] reads them. Lets an app find what keeps it redrawing.
146/// Only with the `frame-stats` feature: otherwise nothing is counted.
147#[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/// `window.request_animation_frame()`, counted by [`take_frame_requests`] at the caller's
158/// line like the frames of the motion helpers. For an app's own frame-by-frame animation, so
159/// a window that keeps redrawing shows who asked.
160#[track_caller]
161pub fn request_animation_frame(window: &mut Window) {
162    request_frame(window);
163}
164
165/// [`request_frame`] for the element `id`: with `frame-stats`, [`take_frame_requests`] also
166/// says which element asked most from each call site (one call site serves every row of a
167/// list, and the row is what you need to find).
168#[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/// The id [`request_frame_for`] reports: kept only with `frame-stats` (nothing to clone
178/// otherwise).
179#[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/// Distinct elements remembered per call site between two [`take_frame_requests`].
196#[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    /// Per call site, the elements that requested frames from it (see [`request_frame_for`]).
205    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/// Counts a frame request from the caller's call site (see [`take_frame_requests`]). The
228/// timed redraws of [`continuous_at`] count too: they are frames as much as an animation
229/// frame, and without them a window kept busy by spinners showed no culprit.
230#[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
244/// Shared grid for timed redraws, in ticks per second. Every [`tick_delay`] lands on it, so a
245/// spinner at 30 fps, a caret at 4 fps and an app's coalesced updates fire at the same
246/// instants and GPUI draws them in one frame instead of interleaving them (30 + 33 updates
247/// per second used to be ~50 frames).
248const TICK_GRID: f64 = 60.;
249
250/// Start of the tick grid (not scaled by the motion settings: it paces timers, not values).
251fn tick_origin() -> Instant {
252    static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
253    *START.get_or_init(Instant::now)
254}
255
256/// Time until the next tick of a `fps` ticker on the shared grid. Use it to pace redraws that
257/// do not need every frame (streamed text, clocks): `fps` ticks per second at most, in step
258/// with the motion helpers' own timed redraws.
259pub 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
264/// Seconds from `now` (seconds since the grid origin) to the next multiple of `1 / fps`,
265/// moved forward onto the [`TICK_GRID`] when that multiple is not on it. Never zero, so a
266/// redraw that lands right on a tick waits for the next one instead of firing twice.
267fn 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        // `now` is on a tick (float error put it just before): the next one.
272        next += period;
273    }
274    // The epsilon keeps a tick that is already on the grid (k/30 → 2k/60) from rounding a
275    // whole grid step up because of float error.
276    let next = ((next * TICK_GRID) - 1e-6).ceil() / TICK_GRID;
277    (next - now).max(1e-4)
278}
279
280/// The frame requests since the last call, as `file:line` and count, most frequent first.
281/// When the call site animates elements by id, the one that asked most follows in brackets
282/// with its own count (`file:line [row-12 ×40]`). Always empty without the `frame-stats`
283/// feature.
284pub 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/// Clock for a continuous animation: requests the next frame and returns the current time.
313/// With reduced motion it always returns 0 and requests no frames (the animation stays still).
314#[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
323/// Frame rate cap for [`continuous_at`] while its window is not the active one.
324const BACKGROUND_FPS: f32 = 4.;
325
326thread_local! {
327    /// Views that already have a redraw scheduled by [`continuous_at`] (avoids piling up timers).
328    static PENDING: RefCell<HashSet<EntityId>> = RefCell::new(HashSet::new());
329    /// Per window, the ambient clock of [`ambient_clock`].
330    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    /// Moves the clock to `now` and returns the time to show. It advances only while the window
351    /// stays active and nothing holds it, and the first call after a hold does not advance, so
352    /// the shapes resume from the pose they held instead of jumping ahead.
353    fn advance(&mut self, now: f32, active: bool, held: bool) -> f32 {
354        // A long gap (nothing was drawing it) is not time the shapes should catch up on.
355        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
365/// Clock for slow ambient motion that stops while the window is in the background and
366/// resumes from where it was, so the shapes neither jump to their first pose when focus
367/// changes nor leap ahead when it returns. 0 with reduced motion.
368pub fn ambient_clock(window: &Window, cx: &App) -> f32 {
369    ambient_tick(window, cx, false)
370}
371
372/// [`ambient_clock`] held still: returns the pose it was at and keeps it there (see
373/// [`crate::Shape::ambient`]).
374pub(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/// Like [`continuous`], but at `fps` frames per second. For slow ambient motion
393/// (shapes that breathe or rotate slowly) 30 fps looks the same and costs half as much.
394#[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    // In a background window it keeps moving (it may still be on screen), but slower:
400    // every tick redraws the whole view, not just the 16 px spinner.
401    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        // On the shared grid: other timed redraws of this window land on the same frame.
414        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/// State of an `N`-channel value that follows its target with a spring.
426#[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    /// Current value and velocity.
449    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    /// Advances to the current instant; returns the value and whether it is still moving.
463    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    /// Launches the value from `from` toward the current target (for entrance animations).
496    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/// Animates `target` with a spring and returns this frame's value.
507///
508/// `id` identifies the value across frames (must be unique within the view). The first frame
509/// returns the target directly; use [`animate_from`] to animate the entrance.
510#[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/// Like [`animate`], but the first frame starts from `from` (spring entrance).
522#[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        // Shortcut: a value at rest with the same target needs no computation.
557        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        // Retargeted again right after starting: two live elements share this id and keep
563        // flipping each other's target every frame, so the window never stops redrawing.
564        #[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
576/// Plain state tied to `id` that lives as long as the element is drawn in consecutive frames.
577/// Lighter than `use_keyed_state` (creates no entity or observer).
578pub(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/// Each time `active` goes from `false` to `true`, the value jumps to `from` and springs back
594/// to `rest` (e.g. the icon that "pops" when a tab is selected).
595#[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            // Anything already active when it appears also animates its entrance.
612            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/// Entrance progress (0 → 1, with the spring's bounce) since the element appeared,
638/// after `delay` seconds. Useful for staggering lists and menus.
639#[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/// Like [`entrance`], but from `start`, an instant the caller keeps (when a message arrived,
667/// when an event happened) instead of when the element was first drawn. Drawing the element
668/// again later (a list row that scrolls back into view, a view that is rebuilt) does not play
669/// the entrance again, and showing it halfway through shows it halfway. Requests frames only
670/// until it settles; 1 with reduced motion.
671#[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
691/// Progress of an entrance `t` seconds after it starts (negative: still waiting for its
692/// delay), or `None` once it has settled and needs no more frames.
693fn 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/// Shortcut for animating a single number.
698#[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/// Shortcut for animating a length in pixels.
710#[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/// Shortcut for animating a color (interpolated in sRGB; no bounce when using an effects spring).
722#[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
741/// Cubic Bézier curve (like CSS `cubic-bezier()`).
742pub 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/// Stable child key for a component's animated values.
772/// Opacity for pulsing text ("Working…"): 1 → 0.45 → 1 every `period` seconds, at 30 fps.
773/// With reduced motion it stays at 1.
774#[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/// Time-based replay: returns the seconds elapsed since `generation` last changed, or `None`
784/// once `duration` has passed (and on the first frame, so nothing plays on mount). Use it for
785/// one-shot effects such as the send button's launch or a tab's content fading in.
786#[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/// Seconds since `active` last went from `false` to `true`, while fewer than `duration` have
820/// passed; `None` otherwise (and when it starts active, so nothing plays on mount). Use it for
821/// one-shot effects tied to a state edge, such as a shape that breathes once when hovered.
822#[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/// Keeps something on screen while it animates out.
856///
857/// Returns `Some(progress)` while the content should be drawn: `1.` while `show` is true, then
858/// falling to `0.` with the fast effects spring once `show` turns false (exits are shorter than
859/// entrances). Returns `None` when the exit has finished or when it was never shown. Call it
860/// every frame, shown or not, with the same `id`:
861///
862/// ```ignore
863/// div().when_some(motion::presence("offer", self.offer.is_some(), window, cx), |d, p| {
864///     d.child(banner(&self.last_offer).opacity(p))
865/// })
866/// ```
867///
868/// Keep the data of the leaving content (the last offer, the last menu) until it returns `None`.
869#[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/// What an expanding section should draw this frame. See [`expand`].
918#[derive(Clone, Copy, Debug, PartialEq)]
919pub enum Expand {
920    /// Closed and at rest: draw nothing.
921    Hidden,
922    /// Open and at rest: draw the content at its natural height (it may keep growing).
923    Natural,
924    /// Opening or closing: draw the content clipped to this height.
925    Clipped(Pixels),
926}
927
928struct ExpandState {
929    open: bool,
930    value: Option<SpringValue<1>>,
931}
932
933/// Height animation for content that opens and closes (an expandable card's body).
934///
935/// `measured` is the content's natural height, measured in the previous frame (0 if unknown).
936/// When `open` changes, the height springs between 0 and `measured`; at rest it returns
937/// [`Expand::Natural`] or [`Expand::Hidden`], so open content can change size freely. Nothing
938/// animates on the first frame (content that starts open is just shown).
939#[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        // Opening content that was never measured: lay it out clipped to 0 for one frame.
976        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/// Axis of a [`Enter::shared_axis`] transition.
995#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
996#[non_exhaustive]
997pub enum SharedAxis {
998    /// Sideways: tabs, steps of a flow (forward comes from the right).
999    #[default]
1000    X,
1001    /// Up and down: a list that pages, a stepper (forward comes from below).
1002    Y,
1003    /// In depth: parent and child (GPUI cannot scale, so it only fades in).
1004    Z,
1005}
1006
1007/// An entrance for any element: it slides in from an offset and fades in with a spring,
1008/// optionally after a delay (to stagger a list, see [`stagger`]). Approximates M3's enter
1009/// transitions with offset and opacity (GPUI does not scale elements).
1010///
1011/// ```ignore
1012/// let row = div().child(..);
1013/// let row = Enter::new(("row-in", i)).delay(stagger(i, 0.03, 6)).apply(row, window, cx);
1014/// ```
1015///
1016/// Its state lives while the element is drawn: shown again after being removed, it enters
1017/// again. With [`Enter::on_change`] it plays each time a generation changes instead (new
1018/// content in the same place). Nothing animates with reduced motion, and a finished entrance
1019/// returns the element untouched and requests no frames.
1020#[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    /// Rises 12 px with the spatial spring. `id` must be unique within the view; a new one
1032    /// makes the element enter again.
1033    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    /// The incoming half of an M3 shared axis transition: 30 px along `axis`, from the
1045    /// leading side when `forward` (right or below) and from the trailing side when going
1046    /// back. Use it with [`Enter::on_change`] keyed by the page shown.
1047    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    /// Seconds to wait before starting.
1058    pub fn delay(mut self, delay: f32) -> Self {
1059        self.delay = delay.max(0.);
1060        self
1061    }
1062
1063    /// Where it comes from, in pixels (`dx` > 0: from the right; `dy` > 0: from below).
1064    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    /// Enters each time `generation` changes instead of when it appears.
1076    pub fn on_change(mut self, generation: u64) -> Self {
1077        self.generation = Some(generation);
1078        self
1079    }
1080
1081    /// Progress from 0 to 1 (with the spring's bounce); exactly 1 once finished.
1082    #[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    /// Applies the entrance to `el` (offset and opacity); a finished one returns it untouched.
1097    #[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
1111/// Delay of row `index` of a staggered list: `step` seconds between rows, up to `max` rows so
1112/// a long list does not take long to finish entering.
1113pub 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        // 30 fps: the next multiple of 1/30, always ahead of `now`.
1130        assert!((at(0.010, 30.) - 1. / 30.).abs() < 1e-9);
1131        assert!((at(1. / 30., 30.) - 2. / 30.).abs() < 1e-9);
1132        // A caret at 4 fps and a spinner at 30 fps tick on the same 60 Hz grid.
1133        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        // A rate that is not on the grid moves forward onto it.
1139        let t = at(0.0, 24.);
1140        assert!(t >= 1. / 24. && on_grid(t));
1141        // Never fires twice on the same tick, never waits more than a period plus a grid step.
1142        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        // Damping 0.6 overshoots about 9.5%, like the reference CSS curve (1.093).
1191        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        // Changing the target mid-flight continues from where the value is, without a jump.
1213        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    /// Frames `update` asks for (calls that return `moving`) when sampled at 120 fps for
1219    /// `seconds` toward `target`.
1220    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            // A hover layer (0 → 1) and a size in pixels (0 → 600 px).
1231            for target in [1., 600.] {
1232                let mut value = SpringValue::new(spring, [0.]);
1233                let busy = moving_frames(&mut value, target, 2.);
1234                // It moves for a while and then rests within about twice its settle time.
1235                let limit = (spring.settle_time().as_secs_f32() * 2. * 120.) as usize;
1236                assert!(busy > 0 && busy < limit, "{spring:?} → {target}: {busy} frames");
1237                // At rest with the same target: nothing, however late it is drawn again.
1238                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            // Waiting for its delay: drawn at the start, still asking for frames.
1250            assert_eq!(entrance_progress(spring, -0.1), Some(0.));
1251            assert!(entrance_progress(spring, settle * 0.5).is_some());
1252            // Settled: no frames, at any later time (an event's clock keeps running).
1253            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        // Held: the pose stays put while time goes by.
1264        assert!(close(clock.advance(11., true, true), 10.5));
1265        assert!(close(clock.advance(40., true, true), 10.5));
1266        // Resumed: the first frame shows the held pose, then it moves on at the normal pace.
1267        assert!(close(clock.advance(60., true, false), 10.5));
1268        assert!(close(clock.advance(60.1, true, false), 10.6));
1269        // In the background it does not move either.
1270        assert!(close(clock.advance(61., false, false), 10.6));
1271    }
1272}