Skip to main content

nsh_core/element/
animated.rs

1//! Native animation values for Rust components (TS: `createAnimatedValue`,
2//! `Animated.spring`, `interpolate`): nodes of the platform's animation
3//! graph that styles, drags, scroll offsets and drawings are bound to, so
4//! they move on the UI thread with no engine work per frame. Composed
5//! animations ([`Animation`], TS: `Animated.sequence` and co.) run there
6//! too, step after step.
7//!
8//! Ids are odd (JS gives its own nodes, animations and composites even
9//! ones), so the graph, which indexes nodes by id, stays dense.
10//!
11//! [`AnimatedValue`] and [`AnimatedNode`] are `Copy` handles: the reactive
12//! owner current when one is made (the component, a region, a row) keeps
13//! its node, and releases it when it is disposed. Used after that, a
14//! handle does nothing (its derivations are gone as well). What binds a
15//! node keeps it while bound ([`LiveNode`]: an element's styles, drags and
16//! scroll offsets, a drawing, a composed animation, a derived node's
17//! inputs), so a binding in a region that outlives the handle's owner
18//! goes on moving, and an animation running on it goes on running.
19//! Listeners and tasks run under the owner that made them, so what they
20//! make is that owner's too; deriving a node again under an owner that
21//! has a handle of it returns that handle ([`Derived`]), so code run over
22//! and over adds nothing. Made with no owner at all (outside any
23//! component), a handle keeps its node as long as the surface, as a
24//! signal made there lives as long as the graph.
25
26use std::{
27    cell::Cell,
28    fmt,
29    rc::{Rc, Weak},
30};
31
32use super::{
33    AdaptiveColor,
34    reactive::{Kept, Owner},
35    task::{Action, Answer, Executor},
36};
37use crate::animation::{
38    AnimationId, AnimationOp, Composite, Driver, Easing, Extrapolate, Keyframe, KeyframeTiming,
39    MathOp, MotionChannel, MotionSpec, Operand, Output, StaggerFrom,
40};
41
42/// A node of the graph, released when the last of what holds it goes
43/// (the owner of its handles, its bindings, the nodes derived from it).
44pub(crate) struct Node {
45    id: crate::animation::NodeId,
46    executor: Weak<Executor>,
47    /// The nodes it derives from, alive while it is: a chain such as
48    /// `v.mul(TAU).sub(1.0)` keeps no handle of its middle node.
49    _inputs: Vec<Rc<Node>>,
50}
51
52impl Node {
53    fn new(
54        executor: &Rc<Executor>,
55        op: impl FnOnce(crate::animation::NodeId) -> AnimationOp,
56        inputs: Vec<Rc<Node>>,
57    ) -> Rc<Self> {
58        let id = executor.next_animation_id();
59        executor.act(Action::Animation(op(id)));
60        Rc::new(Self {
61            id,
62            executor: Rc::downgrade(executor),
63            _inputs: inputs,
64        })
65    }
66
67    fn act(&self, op: AnimationOp) {
68        if let Some(executor) = self.executor.upgrade() {
69            executor.act(Action::Animation(op));
70        }
71    }
72}
73
74impl Drop for Node {
75    fn drop(&mut self) {
76        self.act(AnimationOp::Release { node: self.id });
77    }
78}
79
80/// `op` (a node-making operation) making node `id`.
81fn with_node(mut op: AnimationOp, id: crate::animation::NodeId) -> AnimationOp {
82    match &mut op {
83        AnimationOp::CreateValue { node, .. }
84        | AnimationOp::CreateInterpolate { node, .. }
85        | AnimationOp::CreateDiffClamp { node, .. }
86        | AnimationOp::CreateMath { node, .. } => *node = id,
87        _ => {}
88    }
89    op
90}
91
92/// Derived nodes by what made them ([`DerivedKey`]), while alive, with the
93/// handles of each that owners keep: deriving a node again under an owner
94/// that has a handle of it returns that handle, so doing it over and over
95/// (in a listener, a binding run again) adds nothing.
96///
97/// Kept by a hash of their keys, so a derive looks at the few of the same
98/// hash, not at every derived node: deriving a graph's nodes one by one
99/// costs time that grows with their number, not with its square.
100#[derive(Default)]
101pub(crate) struct Derived {
102    by_hash: rustc_hash::FxHashMap<u64, Vec<DerivedNode>>,
103    /// Nodes added since dead ones were last swept out.
104    added: usize,
105    /// How many were live then.
106    live: usize,
107}
108
109/// What makes a derived node: its operation (node id 0) and, for colors
110/// that follow the appearance, the dark ones (the operation has the light
111/// ones, whichever appearance is current), so interpolations sharing their
112/// light colors are not one node, and neither are a constant one and an
113/// adaptive one.
114#[derive(Clone, PartialEq)]
115struct DerivedKey {
116    op: AnimationOp,
117    dark: Option<Output>,
118}
119
120struct DerivedNode {
121    key: DerivedKey,
122    node: Weak<Node>,
123    /// The live handles of it, by the owner keeping each.
124    handles: Vec<(Owner, AnimatedNode)>,
125}
126
127impl DerivedKey {
128    /// A hash of the key, alike for equal keys: the operation's kind, its
129    /// inputs and its numbers (by their bits, both zeros as one).
130    fn hash(&self) -> u64 {
131        use std::hash::{Hash, Hasher};
132        fn number(h: &mut rustc_hash::FxHasher, v: f32) {
133            (if v == 0.0 { 0 } else { v.to_bits() }).hash(h);
134        }
135        fn operand(h: &mut rustc_hash::FxHasher, o: &Operand) {
136            match *o {
137                Operand::Node(n) => n.hash(h),
138                Operand::Const(c) => number(h, c),
139            }
140        }
141        let mut h = rustc_hash::FxHasher::default();
142        std::mem::discriminant(&self.op).hash(&mut h);
143        match &self.op {
144            AnimationOp::CreateInterpolate {
145                input,
146                input_range,
147                output,
148                ..
149            } => {
150                input.hash(&mut h);
151                input_range.iter().for_each(|&v| number(&mut h, v));
152                match output {
153                    Output::Numbers(v) => v.iter().for_each(|&v| number(&mut h, v)),
154                    Output::Colors(v) => v.hash(&mut h),
155                }
156            }
157            AnimationOp::CreateMath { a, b, .. } => {
158                operand(&mut h, a);
159                operand(&mut h, b);
160            }
161            AnimationOp::CreateDiffClamp {
162                input, min, max, ..
163            } => {
164                input.hash(&mut h);
165                operand(&mut h, min);
166                operand(&mut h, max);
167            }
168            _ => {}
169        }
170        h.finish()
171    }
172}
173
174impl Derived {
175    /// The live node `key` made.
176    fn entry(&mut self, key: &DerivedKey) -> Option<&mut DerivedNode> {
177        let same = self.by_hash.get_mut(&key.hash())?;
178        same.retain(|d| d.node.strong_count() > 0);
179        same.iter_mut().find(|d| d.key == *key)
180    }
181
182    /// Adds `node`, newly made. Dead nodes are swept out once as many were
183    /// added as lived at the last sweep, so sweeping costs each addition a
184    /// share of one pass.
185    fn add(&mut self, node: DerivedNode) {
186        self.added += 1;
187        if self.added > self.live.max(64) {
188            self.by_hash.retain(|_, same| {
189                same.retain(|d| d.node.strong_count() > 0);
190                !same.is_empty()
191            });
192            self.live = self.by_hash.values().map(Vec::len).sum();
193            self.added = 0;
194        }
195        self.by_hash.entry(node.key.hash()).or_default().push(node);
196    }
197}
198
199/// A value of the graph: [`AnimatedValue`] or [`AnimatedNode`], to bind
200/// (`Styled::bind_opacity`) or derive from.
201pub trait Animated {
202    /// The node.
203    fn animated_node(&self) -> AnimatedNode;
204}
205
206/// A node of the graph held while something is bound to it (an element's
207/// style or gesture, a drawing, a composed animation): it outlives the
208/// owner of the handle it came from for as long as it is held.
209#[derive(Clone)]
210pub(crate) struct LiveNode(Rc<Node>);
211
212impl LiveNode {
213    pub(crate) fn id(&self) -> crate::animation::NodeId {
214        self.0.id
215    }
216
217    fn act(&self, op: AnimationOp) {
218        self.0.act(op);
219    }
220
221    fn executor(&self) -> Option<Rc<Executor>> {
222        self.0.executor.upgrade()
223    }
224}
225
226impl PartialEq for LiveNode {
227    fn eq(&self, other: &Self) -> bool {
228        self.id() == other.id()
229    }
230}
231
232impl fmt::Debug for LiveNode {
233    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234        f.debug_tuple("LiveNode").field(&self.id()).finish()
235    }
236}
237
238/// A node derived from values (an interpolation, arithmetic): bound like a
239/// value, moving when they move. A `Copy` handle, kept by the owner it was
240/// made under (see the module's docs).
241#[derive(Clone, Copy)]
242pub struct AnimatedNode {
243    node: Kept<Node>,
244    /// The node's id, for what names it (styles, equality) without
245    /// reaching it.
246    id: crate::animation::NodeId,
247}
248
249impl AnimatedNode {
250    /// Keeps `node` in the current owner.
251    fn keep(node: Rc<Node>) -> Self {
252        let id = node.id;
253        Self {
254            node: Kept::new(node),
255            id,
256        }
257    }
258
259    /// A handle of no node (made from a handle whose owner is gone).
260    fn gone() -> Self {
261        Self {
262            node: Kept::gone(),
263            id: 0,
264        }
265    }
266
267    pub(crate) fn id(&self) -> crate::animation::NodeId {
268        self.id
269    }
270
271    /// The node, while the owner of the handle lives: what a binding
272    /// holds.
273    pub(crate) fn live(&self) -> Option<LiveNode> {
274        self.node.get().map(LiveNode)
275    }
276
277    /// Sends `op` to the graph while the node is live (queuing it reaches
278    /// only the executor, never the reactive graph).
279    fn act(&self, op: impl FnOnce(crate::animation::NodeId) -> AnimationOp) {
280        let id = self.id;
281        self.node.with(|node| node.act(op(id)));
282    }
283
284    /// Where the node's operations go, while it is live.
285    fn executor(&self) -> Option<Rc<Executor>> {
286        self.node.with(|node| node.executor.upgrade()).flatten()
287    }
288
289    /// The node `key` makes from this one: the live one made by the same
290    /// key if there is one (a region or a row made again derives it again
291    /// and gets the same node, so its bindings stay as they are), through
292    /// the handle the current owner keeps of it (made the first time), and
293    /// whether that handle is new. A new node is made by `now` if given (the
294    /// current appearance's colors), else by the key's operation. Of a node
295    /// whose owner is gone (or with an operand whose owner is gone): no
296    /// node.
297    fn derive(
298        &self,
299        key: DerivedKey,
300        now: Option<AnimationOp>,
301        others: &[Option<AnimatedNode>],
302    ) -> (AnimatedNode, bool) {
303        let Some(node) = self.live() else {
304            return (Self::gone(), false);
305        };
306        let mut live = Vec::new();
307        for other in others.iter().flatten() {
308            match other.live() {
309                Some(other) => live.push(other),
310                None => return (Self::gone(), false),
311            }
312        }
313        let Some(executor) = node.executor() else {
314            // The surface is gone: a node nothing reads.
315            return (*self, false);
316        };
317        let owner = Owner::current();
318        let mut derived = executor.derived();
319        if let Some(entry) = derived.entry(&key) {
320            entry.handles.retain(|(_, h)| h.node.is_live());
321            if let Some(&(_, handle)) = entry.handles.iter().find(|(o, _)| *o == owner) {
322                return (handle, false);
323            }
324            let Some(node) = entry.node.upgrade() else {
325                unreachable!("entries are of live nodes");
326            };
327            let handle = Self::keep(node);
328            entry.handles.push((owner, handle));
329            return (handle, true);
330        }
331        drop(derived);
332        let mut inputs = vec![node.0];
333        inputs.extend(live.into_iter().map(|o| o.0));
334        let op = now.unwrap_or_else(|| key.op.clone());
335        let node = Node::new(&executor, |id| with_node(op, id), inputs);
336        let weak = Rc::downgrade(&node);
337        let handle = Self::keep(node);
338        executor.derived().add(DerivedNode {
339            key,
340            node: weak,
341            handles: vec![(owner, handle)],
342        });
343        (handle, true)
344    }
345
346    /// Maps the value through `input` breakpoints (ascending) to numbers,
347    /// clamped at both ends: `x.interpolate(&[0.0, 300.0], &[1.0, 0.0])`.
348    pub fn interpolate(&self, input: &[f32], output: &[f32]) -> AnimatedNode {
349        self.interpolate_with(
350            input,
351            Output::Numbers(output.to_vec()),
352            Interpolation::default(),
353        )
354    }
355
356    /// Maps the value to colors (`backgroundColor` bindings). Theme colors
357    /// (`AdaptiveColor`s) follow the appearance: when it changes, the node
358    /// takes the other appearance's colors in place, its bindings as they
359    /// are.
360    pub fn interpolate_colors<C: Into<AdaptiveColor> + Copy>(
361        &self,
362        input: &[f32],
363        colors: &[C],
364    ) -> AnimatedNode {
365        let colors: Rc<[AdaptiveColor]> = colors.iter().map(|&c| c.into()).collect();
366        let pick = {
367            let colors = colors.clone();
368            move |dark: bool| {
369                Output::Colors(
370                    colors
371                        .iter()
372                        .map(|c| crate::style::Color::from(if dark { c.dark } else { c.light }).0)
373                        .collect(),
374                )
375            }
376        };
377        if colors.iter().all(|c| c.light == c.dark) {
378            return self.interpolate_with(input, pick(false), Interpolation::default());
379        }
380        let (node, new) = self.interpolate_derived(
381            input,
382            pick(false),
383            Some(pick(true)),
384            Interpolation::default(),
385        );
386        // The appearance's colors from now on; the effect holds the node
387        // while it lives (it goes with the owner that keeps the handle,
388        // which has one already when the handle is not new).
389        let Some(held) = node.live().filter(|_| new) else {
390            return node;
391        };
392        let first = Cell::new(true);
393        super::reactive::render_effect(move || {
394            let output = pick(super::dark());
395            if !first.replace(false) {
396                held.act(AnimationOp::SetOutput {
397                    node: held.id(),
398                    output,
399                });
400            }
401        });
402        node
403    }
404
405    /// [`Self::interpolate`] with any output, extrapolation on each side
406    /// and curve (TS: `interpolate({ extrapolateLeft, extrapolateRight,
407    /// easing })`).
408    pub fn interpolate_with(
409        &self,
410        input: &[f32],
411        output: Output,
412        interpolation: Interpolation,
413    ) -> AnimatedNode {
414        self.interpolate_derived(input, output, None, interpolation)
415            .0
416    }
417
418    /// [`Self::interpolate_with`] to `output`, or, with `dark`, to the
419    /// current appearance's of `output` (light) and `dark`; and whether its
420    /// handle is new.
421    fn interpolate_derived(
422        &self,
423        input: &[f32],
424        output: Output,
425        dark: Option<Output>,
426        interpolation: Interpolation,
427    ) -> (AnimatedNode, bool) {
428        let op = |output| AnimationOp::CreateInterpolate {
429            node: 0,
430            input: self.id(),
431            input_range: input.to_vec(),
432            output,
433            extrapolate_left: interpolation.extrapolate_left,
434            extrapolate_right: interpolation.extrapolate_right,
435            easing: interpolation.easing,
436        };
437        let now = dark
438            .clone()
439            .filter(|_| super::untracked(super::dark))
440            .map(op);
441        self.derive(
442            DerivedKey {
443                op: op(output),
444                dark,
445            },
446            now,
447            &[],
448        )
449    }
450
451    fn math(&self, op: MathOp, other: AnimationOperand) -> AnimatedNode {
452        let a = Operand::Node(self.id());
453        let b = other.operand;
454        let op = AnimationOp::CreateMath { node: 0, op, a, b };
455        self.derive(DerivedKey { op, dark: None }, None, &[other.node])
456            .0
457    }
458
459    /// The sum with `other`.
460    pub fn add(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
461        self.math(MathOp::Add, other.into())
462    }
463
464    /// The difference with `other`.
465    pub fn sub(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
466        self.math(MathOp::Sub, other.into())
467    }
468
469    /// The product with `other`.
470    pub fn mul(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
471        self.math(MathOp::Mul, other.into())
472    }
473
474    /// The quotient by `other`.
475    pub fn div(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
476        self.math(MathOp::Div, other.into())
477    }
478
479    /// The remainder by `other`.
480    pub fn modulo(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
481        self.math(MathOp::Mod, other.into())
482    }
483
484    /// Follows the value's changes but stays within `min..=max` (a header
485    /// hiding as content scrolls up). Each bound is a number or another
486    /// animated value, read at each evaluation: a range that changes while
487    /// dragging clamps at its current bounds.
488    pub fn diff_clamp(
489        &self,
490        min: impl Into<AnimationOperand>,
491        max: impl Into<AnimationOperand>,
492    ) -> AnimatedNode {
493        self.diff_clamp_with(min, max, DiffClamp::default())
494    }
495
496    /// [`Self::diff_clamp`] with options: [`DiffClamp::snapping`] settles at
497    /// the nearer bound when the scroll view the value follows comes to rest
498    /// (TS: `diffClamp(min, max, { snap: true })`).
499    pub fn diff_clamp_with(
500        &self,
501        min: impl Into<AnimationOperand>,
502        max: impl Into<AnimationOperand>,
503        options: DiffClamp,
504    ) -> AnimatedNode {
505        let (min, max) = (min.into(), max.into());
506        let op = AnimationOp::CreateDiffClamp {
507            node: 0,
508            input: self.id(),
509            min: min.operand,
510            max: max.operand,
511            snap: options.snap,
512        };
513        self.derive(DerivedKey { op, dark: None }, None, &[min.node, max.node])
514            .0
515    }
516}
517
518/// Options of [`AnimatedNode::diff_clamp_with`] (TS: `diffClamp`'s third
519/// argument). By default it only follows its input.
520#[derive(Debug, Clone, Copy, PartialEq, Default)]
521#[non_exhaustive]
522pub struct DiffClamp {
523    /// When the scroll view the value follows comes to rest between the
524    /// bounds, it settles at the nearer one in 200 ms, easing out: a
525    /// floating bar shows or hides fully. It settles at `max` only once
526    /// the value reached `max`, so a page scrolled less than the bar's
527    /// height shows the whole bar.
528    pub snap: bool,
529}
530
531impl DiffClamp {
532    /// Settles at the nearer bound when its scroll view rests.
533    pub const fn snapping() -> Self {
534        Self { snap: true }
535    }
536}
537
538impl Animated for AnimatedNode {
539    fn animated_node(&self) -> AnimatedNode {
540        *self
541    }
542}
543
544impl PartialEq for AnimatedNode {
545    fn eq(&self, other: &Self) -> bool {
546        self.id() == other.id()
547    }
548}
549
550impl fmt::Debug for AnimatedNode {
551    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
552        f.debug_tuple("AnimatedNode").field(&self.id()).finish()
553    }
554}
555
556/// An operand of arithmetic on nodes: a number or another node.
557#[derive(Debug, Clone)]
558pub struct AnimationOperand {
559    operand: Operand,
560    /// The node, which what derives from it holds.
561    node: Option<AnimatedNode>,
562}
563
564impl From<f32> for AnimationOperand {
565    fn from(n: f32) -> Self {
566        Self {
567            operand: Operand::Const(n),
568            node: None,
569        }
570    }
571}
572
573impl<A: Animated> From<&A> for AnimationOperand {
574    fn from(a: &A) -> Self {
575        let node = a.animated_node();
576        Self {
577            operand: Operand::Node(node.id()),
578            node: Some(node),
579        }
580    }
581}
582
583/// How [`AnimatedNode::interpolate_with`] maps: what it does outside the
584/// input range on each side, and the curve within each segment (TS:
585/// `extrapolateLeft`, `extrapolateRight`, `easing`). By default it clamps
586/// on both sides, linearly.
587#[derive(Debug, Clone, Copy, PartialEq)]
588pub struct Interpolation {
589    /// Below the first breakpoint.
590    pub extrapolate_left: Extrapolate,
591    /// Above the last breakpoint.
592    pub extrapolate_right: Extrapolate,
593    /// The curve within each segment.
594    pub easing: Easing,
595}
596
597impl Interpolation {
598    /// `extrapolate` on both sides, linearly (TS: `extrapolate`).
599    pub const fn extrapolate(extrapolate: Extrapolate) -> Self {
600        Self {
601            extrapolate_left: extrapolate,
602            extrapolate_right: extrapolate,
603            easing: Easing::Linear,
604        }
605    }
606}
607
608impl Default for Interpolation {
609    fn default() -> Self {
610        Self::extrapolate(Extrapolate::Clamp)
611    }
612}
613
614/// A settable, animatable value (made with
615/// [`super::animated_value`]): set it, animate it, bind it, derive
616/// from it. A `Copy` handle, kept by the owner it was made under: copies
617/// are the same value, closures share it as they share a signal; used
618/// after the owner is gone, it does nothing (see the module's docs).
619#[derive(Clone, Copy, PartialEq, Debug)]
620pub struct AnimatedValue(AnimatedNode);
621
622/// How a spring moves (TS's defaults: stiffness 170, damping 26, mass 1):
623/// an animated value's ([`AnimatedValue::spring`]) and a layout
624/// animation's ([`LayoutTransition::spring`](crate::LayoutTransition::spring)).
625///
626/// Made as `gpui-base`'s `Spring` is, from how long it takes and how much it
627/// overshoots ([`Spring::new`], [`Spring::damping_ratio`]), or from a
628/// stiffness, as Material 3's motion tokens give it
629/// ([`Spring::from_stiffness`]); its fields are the physics either way.
630///
631/// ```
632/// use nsh_core::element::Spring;
633///
634/// // `gpui-component`'s `spring_move`: a 280 ms response, a little springy.
635/// let spring = Spring::new(280.0).damping_ratio(0.85);
636/// assert!((spring.settle_ms() - 362.2).abs() < 0.1);
637/// // Material 3 Expressive's fast spatial spring.
638/// let spring = Spring::from_stiffness(800.0).damping_ratio(0.6);
639/// assert!((spring.settle_ms() - 407.0).abs() < 0.1);
640/// ```
641#[derive(Debug, Clone, Copy, PartialEq)]
642pub struct Spring {
643    /// Stiffness `k`.
644    pub stiffness: f32,
645    /// Damping coefficient `c` (not a ratio: the ratio is `c / (2 √(k m))`,
646    /// [`Spring::damping_ratio`] sets it).
647    pub damping: f32,
648    /// Mass `m`.
649    pub mass: f32,
650    /// The velocity it starts with (per second); `None` keeps the current
651    /// one.
652    pub velocity: Option<f32>,
653    /// The highest frame rate it needs, in Hz (TS's `frameRate`); `None`:
654    /// the screen's highest ([`Driver::frame_rate`]).
655    pub frame_rate: Option<f32>,
656}
657
658impl Default for Spring {
659    fn default() -> Self {
660        Self {
661            stiffness: 170.0,
662            damping: 26.0,
663            mass: 1.0,
664            velocity: None,
665            frame_rate: None,
666        }
667    }
668}
669
670/// How a timing animation moves (TS's defaults: 300 ms, ease in-out, no
671/// delay).
672#[derive(Debug, Clone, Copy, PartialEq)]
673pub struct Timing {
674    /// How long it takes, in milliseconds.
675    pub duration_ms: f32,
676    /// The curve.
677    pub easing: Easing,
678    /// How long it waits before it starts, in milliseconds.
679    pub delay_ms: f32,
680    /// The highest frame rate it needs, in Hz (TS's `frameRate`); `None`:
681    /// the screen's highest ([`Driver::frame_rate`]).
682    pub frame_rate: Option<f32>,
683}
684
685impl Timing {
686    /// `duration_ms` along `easing`, with no delay.
687    pub const fn new(duration_ms: f32, easing: Easing) -> Self {
688        Self {
689            duration_ms,
690            easing,
691            delay_ms: 0.0,
692            frame_rate: None,
693        }
694    }
695
696    /// Needing at most `hz` frames per second (a slow fade: 30).
697    pub const fn frame_rate(mut self, hz: f32) -> Self {
698        self.frame_rate = Some(hz);
699        self
700    }
701
702    fn driver(self, to: f32) -> Driver {
703        Driver::Timing {
704            to,
705            duration_ms: self.duration_ms,
706            easing: self.easing,
707            delay_ms: self.delay_ms,
708            frame_rate: self.frame_rate,
709        }
710    }
711}
712
713impl Default for Timing {
714    fn default() -> Self {
715        Self::new(300.0, Easing::EaseInOut)
716    }
717}
718
719impl Spring {
720    /// `gpui-base`'s `Spring::new(response)`: a mass of 1 that would swing
721    /// once in `response_ms` undamped, critically damped (no overshoot).
722    /// The response is the scale the motion is felt at, not when it stops
723    /// ([`Spring::settle_ms`]).
724    pub fn new(response_ms: f32) -> Self {
725        let omega = std::f32::consts::TAU / (response_ms / 1000.0);
726        Self {
727            stiffness: omega * omega,
728            damping: 2.0 * omega,
729            mass: 1.0,
730            velocity: None,
731            frame_rate: None,
732        }
733    }
734
735    /// A mass of 1 on a spring of `stiffness`, critically damped: a design
736    /// system's stiffness token, its damping ratio set with
737    /// [`Spring::damping_ratio`].
738    pub fn from_stiffness(stiffness: f32) -> Self {
739        Self {
740            stiffness,
741            damping: 2.0 * stiffness.max(0.0).sqrt(),
742            mass: 1.0,
743            velocity: None,
744            frame_rate: None,
745        }
746    }
747
748    /// Damped at `ratio` (`gpui-base`'s `with_damping`): 1 does not
749    /// overshoot, below 1 it passes its target and comes back, above 1 it
750    /// approaches slowly. Sets [`Spring::damping`] from the stiffness and
751    /// mass it has, so set those first.
752    pub fn damping_ratio(mut self, ratio: f32) -> Self {
753        self.damping = 2.0 * ratio * (self.stiffness * self.mass).max(0.0).sqrt();
754        self
755    }
756
757    /// How far it has gone, from 0 to 1, `ms` milliseconds after it was
758    /// released at rest: the damped oscillator's closed form, past 1 when
759    /// it is underdamped. A spring that never settles (no damping, or a
760    /// stiffness or mass that is not positive) is at 1 at once.
761    pub fn progress(self, ms: f32) -> f32 {
762        let Some((zeta, omega)) = self.oscillator() else {
763            return 1.0;
764        };
765        if ms <= 0.0 {
766            return 0.0;
767        }
768        let t = ms / 1000.0;
769        if (zeta - 1.0).abs() < CRITICAL {
770            return 1.0 - (1.0 + omega * t) * (-omega * t).exp();
771        }
772        if zeta < 1.0 {
773            let decay = zeta * omega;
774            let wd = omega * (1.0 - zeta * zeta).sqrt();
775            return 1.0 - (-decay * t).exp() * ((wd * t).cos() + decay / wd * (wd * t).sin());
776        }
777        let root = omega * (zeta * zeta - 1.0).sqrt();
778        let (slow, fast) = (zeta * omega - root, zeta * omega + root);
779        1.0 - (fast * (-slow * t).exp() - slow * (-fast * t).exp()) / (fast - slow)
780    }
781
782    /// How long it takes, in milliseconds, released at rest, to stay within
783    /// a thousandth of its travel: how long a layout animation on it lasts.
784    /// 0 for a spring that never settles.
785    pub fn settle_ms(self) -> f32 {
786        let Some((zeta, omega)) = self.oscillator() else {
787            return 0.0;
788        };
789        let seconds = if (zeta - 1.0).abs() < CRITICAL {
790            // (1 + ω t) e^(-ω t) falls to 1/1000 at ω t = 9.233.
791            9.233 / omega
792        } else if zeta < 1.0 {
793            SETTLE / (zeta * omega)
794        } else {
795            // The slow root's term, whose weight is above 1, outlasts the fast one's.
796            let root = (zeta * zeta - 1.0).sqrt();
797            let weight = (zeta + root) / (2.0 * root);
798            (SETTLE + weight.ln()) / (omega * (zeta - root))
799        };
800        seconds * 1000.0
801    }
802
803    /// The damping ratio and the natural angular frequency (radians per
804    /// second); `None` when it never settles.
805    fn oscillator(self) -> Option<(f32, f32)> {
806        let Spring {
807            stiffness,
808            damping,
809            mass,
810            ..
811        } = self;
812        if !(stiffness > 0.0 && mass > 0.0 && damping > 0.0)
813            || !(stiffness.is_finite() && mass.is_finite() && damping.is_finite())
814        {
815            return None;
816        }
817        let zeta = damping / (2.0 * (stiffness * mass).sqrt());
818        Some((zeta, (stiffness / mass).sqrt()))
819    }
820
821    /// Needing at most `hz` frames per second (a small, slow spring: 60).
822    pub const fn frame_rate(mut self, hz: f32) -> Self {
823        self.frame_rate = Some(hz);
824        self
825    }
826
827    fn driver(self, to: f32) -> Driver {
828        Driver::Spring {
829            to,
830            stiffness: self.stiffness,
831            damping: self.damping,
832            mass: self.mass,
833            velocity: self.velocity,
834            frame_rate: self.frame_rate,
835        }
836    }
837}
838
839/// ln(1000): a decay of e^(-x) falls to a thousandth at this x.
840const SETTLE: f32 = 6.907_755;
841
842/// How close to 1 a damping ratio is taken as critical, where the
843/// underdamped and overdamped forms divide by almost 0.
844const CRITICAL: f32 = 1e-3;
845
846/// The values `driver` moves a value through from `from`, one per frame at
847/// `fps` (1 to 1000), until it ends: the exact curve the graph runs.
848fn sample(driver: Driver, from: f32, fps: f32) -> Vec<f32> {
849    let step = 1.0 / f64::from(fps.clamp(1.0, 1000.0));
850    crate::animation::sample_driver(driver, from, step, crate::animation::MAX_SAMPLES)
851}
852
853/// The values a spring moves a value through from `from` to `to`, one per
854/// frame at `fps` (60 on most screens) until it rests (TS:
855/// `Animated.sampleSpring`): its curve, to draw it. At most
856/// [`crate::animation::MAX_SAMPLES`].
857pub fn sample_spring(from: f32, to: f32, spring: Spring, fps: f32) -> Vec<f32> {
858    sample(spring.driver(to), from, fps)
859}
860
861/// The values a decay ([`AnimatedValue::decay`]) moves a value through from
862/// `from` at `velocity` (per second), one per frame at `fps` until it
863/// stops (TS: `Animated.sampleDecay`). At most
864/// [`crate::animation::MAX_SAMPLES`].
865pub fn sample_decay(from: f32, velocity: f32, deceleration: f32, fps: f32) -> Vec<f32> {
866    sample(
867        Driver::Decay {
868            velocity: Some(velocity),
869            deceleration,
870            clamp: None,
871            bounce: 0.0,
872            frame_rate: None,
873        },
874        from,
875        fps,
876    )
877}
878
879/// Like [`sample_decay`], within `min..=max` ([`AnimatedValue::decay_within`]:
880/// it stops at a bound, or bounces back keeping `bounce` of its speed).
881pub fn sample_decay_within(
882    from: f32,
883    velocity: f32,
884    deceleration: f32,
885    (min, max): (f32, f32),
886    bounce: f32,
887    fps: f32,
888) -> Vec<f32> {
889    sample(
890        Driver::Decay {
891            velocity: Some(velocity),
892            deceleration,
893            clamp: Some((min, max)),
894            bounce,
895            frame_rate: None,
896        },
897        from,
898        fps,
899    )
900}
901
902/// The end of an animation: `true` when it reached its end, `false` when
903/// it was stopped or replaced (or never ran: its value's owner was gone).
904/// The animation runs either way: await this in a task to follow it up, or
905/// drop it.
906#[derive(Debug)]
907pub struct AnimationEnd(Answer<bool>);
908
909impl std::future::IntoFuture for AnimationEnd {
910    type Output = bool;
911    type IntoFuture = Answer<bool>;
912
913    fn into_future(self) -> Answer<bool> {
914        self.0
915    }
916}
917
918impl AnimatedValue {
919    pub(crate) fn new(executor: &Rc<Executor>, value: f32) -> Self {
920        Self(AnimatedNode::keep(Node::new(
921            executor,
922            |node| AnimationOp::CreateValue { node, value },
923            Vec::new(),
924        )))
925    }
926
927    /// The node, to derive from.
928    pub fn node(&self) -> &AnimatedNode {
929        &self.0
930    }
931
932    /// Sets the value at once, stopping its animation.
933    pub fn set(&self, value: f32) {
934        self.0.act(|node| AnimationOp::Set { node, value });
935    }
936
937    /// Stops its animation where it is ([`Self::value`] then reads where
938    /// that is; TS: `stop()`'s promise).
939    pub fn stop(&self) {
940        self.0.act(|node| AnimationOp::Stop { node });
941    }
942
943    /// Its value now, read on the UI thread where it moves (TS:
944    /// `getValue()`): after the changes queued before it (a [`Self::stop`],
945    /// a [`Self::set`]). Await it in a task. Once its owner is gone, it
946    /// never comes.
947    pub fn value(&self) -> Answer<f32> {
948        let (answer, slot) = Answer::new();
949        if let Some(executor) = self.0.executor() {
950            executor.act(Action::ReadValue {
951                node: self.0.id(),
952                value: slot,
953            });
954        }
955        answer
956    }
957
958    fn start(&self, driver: Driver) -> AnimationEnd {
959        let (end, slot) = Answer::new();
960        let end = AnimationEnd(end);
961        match self.0.executor() {
962            Some(executor) => {
963                let animation = executor.next_animation_id();
964                executor.act(Action::Animate {
965                    op: AnimationOp::Start {
966                        node: self.0.id(),
967                        animation,
968                        driver,
969                    },
970                    animation,
971                    end: slot,
972                });
973            }
974            // Its owner (or the surface) is gone: it ends at once, unfinished.
975            None => slot.borrow_mut().deliver(false),
976        }
977        end
978    }
979
980    /// Plays `frames` as CSS keyframes play (TS: `keyframes(frames,
981    /// options)`): each segment with its easing, `timing.iterations` times
982    /// in `timing.direction`.
983    pub fn keyframes(
984        &self,
985        frames: impl IntoIterator<Item = Keyframe>,
986        timing: KeyframeTiming,
987    ) -> AnimationEnd {
988        Animation::keyframes(self, frames, timing).start()
989    }
990
991    /// Springs to `to`.
992    pub fn spring(&self, to: f32, spring: Spring) -> AnimationEnd {
993        self.start(spring.driver(to))
994    }
995
996    /// Moves to `to` in `ms` milliseconds along `easing`.
997    pub fn timing(&self, to: f32, ms: f32, easing: Easing) -> AnimationEnd {
998        self.timing_with(to, Timing::new(ms, easing))
999    }
1000
1001    /// Moves to `to` as `timing` says, after its delay.
1002    pub fn timing_with(&self, to: f32, timing: Timing) -> AnimationEnd {
1003        self.start(timing.driver(to))
1004    }
1005
1006    /// Glides from `velocity` (per second; `None`: the current one),
1007    /// slowing down by `deceleration` per millisecond (0.998: a fling).
1008    pub fn decay(&self, velocity: Option<f32>, deceleration: f32) -> AnimationEnd {
1009        self.start(Driver::Decay {
1010            velocity,
1011            deceleration,
1012            clamp: None,
1013            bounce: 0.0,
1014            frame_rate: None,
1015        })
1016    }
1017
1018    /// Like [`Self::decay`], within `min..=max`: it stops at a bound, or
1019    /// bounces back from it keeping `bounce` (0..1) of its speed.
1020    pub fn decay_within(
1021        &self,
1022        velocity: Option<f32>,
1023        deceleration: f32,
1024        (min, max): (f32, f32),
1025        bounce: f32,
1026    ) -> AnimationEnd {
1027        self.start(Driver::Decay {
1028            velocity,
1029            deceleration,
1030            clamp: Some((min, max)),
1031            bounce,
1032            frame_rate: None,
1033        })
1034    }
1035
1036    /// Sets the offset added to the value (React Native's `setOffset`):
1037    /// bindings see value + offset, animations and `set` move the value.
1038    pub fn set_offset(&self, offset: f32) {
1039        self.0.act(|node| AnimationOp::SetOffset { node, offset });
1040    }
1041
1042    /// Adds the offset to the value and clears it.
1043    pub fn flatten_offset(&self) {
1044        self.0.act(|node| AnimationOp::FlattenOffset { node });
1045    }
1046
1047    /// Moves the value into the offset, leaving the value 0 (a drag then
1048    /// starts from where the last one left it).
1049    pub fn extract_offset(&self) {
1050        self.0.act(|node| AnimationOp::ExtractOffset { node });
1051    }
1052
1053    /// See [`AnimatedNode::interpolate`].
1054    pub fn interpolate(&self, input: &[f32], output: &[f32]) -> AnimatedNode {
1055        self.0.interpolate(input, output)
1056    }
1057
1058    /// See [`AnimatedNode::interpolate_colors`].
1059    pub fn interpolate_colors<C: Into<AdaptiveColor> + Copy>(
1060        &self,
1061        input: &[f32],
1062        colors: &[C],
1063    ) -> AnimatedNode {
1064        self.0.interpolate_colors(input, colors)
1065    }
1066
1067    /// See [`AnimatedNode::interpolate_with`].
1068    pub fn interpolate_with(
1069        &self,
1070        input: &[f32],
1071        output: Output,
1072        interpolation: Interpolation,
1073    ) -> AnimatedNode {
1074        self.0.interpolate_with(input, output, interpolation)
1075    }
1076
1077    /// See [`AnimatedNode::diff_clamp`].
1078    pub fn diff_clamp(
1079        &self,
1080        min: impl Into<AnimationOperand>,
1081        max: impl Into<AnimationOperand>,
1082    ) -> AnimatedNode {
1083        self.0.diff_clamp(min, max)
1084    }
1085
1086    /// See [`AnimatedNode::diff_clamp_with`].
1087    pub fn diff_clamp_with(
1088        &self,
1089        min: impl Into<AnimationOperand>,
1090        max: impl Into<AnimationOperand>,
1091        options: DiffClamp,
1092    ) -> AnimatedNode {
1093        self.0.diff_clamp_with(min, max, options)
1094    }
1095
1096    /// See [`AnimatedNode::add`].
1097    pub fn add(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
1098        self.0.add(other)
1099    }
1100
1101    /// See [`AnimatedNode::sub`].
1102    pub fn sub(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
1103        self.0.sub(other)
1104    }
1105
1106    /// See [`AnimatedNode::mul`].
1107    pub fn mul(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
1108        self.0.mul(other)
1109    }
1110
1111    /// See [`AnimatedNode::div`].
1112    pub fn div(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
1113        self.0.div(other)
1114    }
1115
1116    /// See [`AnimatedNode::modulo`].
1117    pub fn modulo(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
1118        self.0.modulo(other)
1119    }
1120}
1121
1122impl Animated for AnimatedValue {
1123    fn animated_node(&self) -> AnimatedNode {
1124        self.0
1125    }
1126}
1127
1128/// A composed animation (TS: `Animated.timing` / `spring` / `decay` /
1129/// `sequence` / `parallel` / `stagger` / `delay` / `loop`): a tree of
1130/// steps over animated values, run on the UI thread, each step starting at
1131/// the exact end of the one before (no round trip to the engine between
1132/// steps).
1133///
1134/// Build it once (in the view, captured by the listeners that run it) and
1135/// run it any number of times: [`Self::start`] runs it (stopping a run of
1136/// it going on) and returns its [`AnimationEnd`], [`Self::stop`] stops it
1137/// where it is, [`Self::reset`] stops it and puts its values back where
1138/// they were when it last started. Clones are the same animation; building a group from
1139/// animations makes a new one (its parts are copied in). It holds the nodes
1140/// of its values while it lives (values whose owner is gone are left
1141/// out), wherever it is kept.
1142///
1143/// ```ignore
1144/// let jump = Animation::sequence([
1145///     Animation::timing(&y, -36.0, Timing::new(220.0, Easing::EaseOut)),
1146///     Animation::spring(&y, 0.0, Spring::default()),
1147/// ]);
1148/// view().on_press(move || {
1149///     let end = jump.start();
1150/// })
1151/// ```
1152#[derive(Clone)]
1153pub struct Animation(Rc<Composed>);
1154
1155struct Composed {
1156    spec: Composite,
1157    /// The nodes of the values it animates, held while it is.
1158    values: Vec<LiveNode>,
1159    run: Run,
1160}
1161
1162/// An animation's identity in the graph.
1163struct Run {
1164    executor: Weak<Executor>,
1165    /// Its composite key (what resets restore by); 0 until it first runs.
1166    key: Cell<u32>,
1167    /// Its last run (0: none).
1168    animation: Cell<AnimationId>,
1169}
1170
1171impl Drop for Run {
1172    fn drop(&mut self) {
1173        // A run going on goes on; the graph forgets the values to reset to.
1174        let key = self.key.get();
1175        if key != 0
1176            && let Some(executor) = self.executor.upgrade()
1177        {
1178            executor.act(Action::Animation(AnimationOp::ReleaseComposite { key }));
1179        }
1180    }
1181}
1182
1183impl Animation {
1184    fn new(spec: Composite, values: Vec<LiveNode>) -> Self {
1185        let executor = values
1186            .first()
1187            .map(|n| n.0.executor.clone())
1188            .unwrap_or_default();
1189        Self(Rc::new(Composed {
1190            spec,
1191            values,
1192            run: Run {
1193                executor,
1194                key: Cell::new(0),
1195                animation: Cell::new(0),
1196            },
1197        }))
1198    }
1199
1200    fn run(value: &AnimatedValue, driver: Driver) -> Self {
1201        let node = value.0.id();
1202        Self::new(
1203            Composite::Run { node, driver },
1204            value.0.live().into_iter().collect(),
1205        )
1206    }
1207
1208    /// `value` moving to `to` as `timing` says.
1209    pub fn timing(value: &AnimatedValue, to: f32, timing: Timing) -> Self {
1210        Self::run(value, timing.driver(to))
1211    }
1212
1213    /// `value` springing to `to`.
1214    pub fn spring(value: &AnimatedValue, to: f32, spring: Spring) -> Self {
1215        Self::run(value, spring.driver(to))
1216    }
1217
1218    /// `value` gliding from `velocity` (per second; `None`: the current
1219    /// one), slowing down by `deceleration` per millisecond (0.998: a
1220    /// fling).
1221    pub fn decay(value: &AnimatedValue, velocity: Option<f32>, deceleration: f32) -> Self {
1222        Self::run(
1223            value,
1224            Driver::Decay {
1225                velocity,
1226                deceleration,
1227                clamp: None,
1228                bounce: 0.0,
1229                frame_rate: None,
1230            },
1231        )
1232    }
1233
1234    /// Like [`Self::decay`], within `min..=max`: it stops at a bound, or
1235    /// bounces back from it keeping `bounce` (0..1) of its speed.
1236    pub fn decay_within(
1237        value: &AnimatedValue,
1238        velocity: Option<f32>,
1239        deceleration: f32,
1240        (min, max): (f32, f32),
1241        bounce: f32,
1242    ) -> Self {
1243        Self::run(
1244            value,
1245            Driver::Decay {
1246                velocity,
1247                deceleration,
1248                clamp: Some((min, max)),
1249                bounce,
1250                frame_rate: None,
1251            },
1252        )
1253    }
1254
1255    /// `value` through `frames`, as CSS keyframes play (TS:
1256    /// `Animated.keyframes`): offsets spread as the Web Animations API
1257    /// spreads them, an easing per segment, iterations, a direction and a
1258    /// delay ([`KeyframeTiming`]).
1259    pub fn keyframes(
1260        value: &AnimatedValue,
1261        frames: impl IntoIterator<Item = Keyframe>,
1262        timing: KeyframeTiming,
1263    ) -> Self {
1264        let frames: Vec<Keyframe> = frames.into_iter().collect();
1265        Self::new(
1266            crate::animation::keyframes(value.0.id(), &frames, &timing),
1267            value.0.live().into_iter().collect(),
1268        )
1269    }
1270
1271    /// A wait of `ms` milliseconds (in a sequence).
1272    pub fn delay(ms: f32) -> Self {
1273        Self::new(Composite::Delay(ms), Vec::new())
1274    }
1275
1276    /// The spec and values of this animation.
1277    fn into_parts(self) -> (Composite, Vec<LiveNode>) {
1278        match Rc::try_unwrap(self.0) {
1279            Ok(Composed { spec, values, .. }) => (spec, values),
1280            Err(shared) => (shared.spec.clone(), shared.values.clone()),
1281        }
1282    }
1283
1284    fn group(
1285        animations: impl IntoIterator<Item = Animation>,
1286        make: impl FnOnce(Vec<Composite>) -> Composite,
1287    ) -> Self {
1288        let mut specs = Vec::new();
1289        let mut values: Vec<LiveNode> = Vec::new();
1290        for animation in animations {
1291            let (spec, of) = animation.into_parts();
1292            specs.push(spec);
1293            for value in of {
1294                if !values.contains(&value) {
1295                    values.push(value);
1296                }
1297            }
1298        }
1299        Self::new(make(specs), values)
1300    }
1301
1302    /// `animations` one after the other; it stops at the first that is
1303    /// stopped.
1304    pub fn sequence(animations: impl IntoIterator<Item = Animation>) -> Self {
1305        Self::group(animations, Composite::Sequence)
1306    }
1307
1308    /// `animations` all at once; one stopped stops the others (see
1309    /// [`Self::stop_together`]).
1310    pub fn parallel(animations: impl IntoIterator<Item = Animation>) -> Self {
1311        Self::group(animations, |children| Composite::Parallel {
1312            children,
1313            stop_together: true,
1314        })
1315    }
1316
1317    /// `animations` all at once, each starting `ms` milliseconds after the
1318    /// one before.
1319    pub fn stagger(ms: f32, animations: impl IntoIterator<Item = Animation>) -> Self {
1320        let staged = animations
1321            .into_iter()
1322            .enumerate()
1323            .map(|(i, a)| Self::sequence([Self::delay(ms * i as f32), a]));
1324        Self::parallel(staged)
1325    }
1326
1327    /// `animations` all at once, each starting `ms` milliseconds after the
1328    /// one before, counted from `from` (TS: `Animated.stagger(ms, list, {
1329    /// from })`): from the center, a list ripples out from its middle.
1330    pub fn stagger_from(
1331        ms: f32,
1332        from: StaggerFrom,
1333        animations: impl IntoIterator<Item = Animation>,
1334    ) -> Self {
1335        let animations: Vec<Animation> = animations.into_iter().collect();
1336        let count = animations.len();
1337        let staged = animations.into_iter().enumerate().map(|(i, a)| {
1338            Self::sequence([
1339                Self::delay(ms * crate::animation::stagger_delay(i, count, from)),
1340                a,
1341            ])
1342        });
1343        Self::parallel(staged)
1344    }
1345
1346    /// This animation over and over: `iterations` times, or until stopped
1347    /// with `None`; its values go back to where they were before each run
1348    /// (see [`Self::reset_before_iteration`]).
1349    pub fn looped(self, iterations: Option<u32>) -> Self {
1350        let (spec, values) = self.into_parts();
1351        Self::new(
1352            Composite::Loop {
1353                child: Box::new(spec),
1354                iterations,
1355                reset: true,
1356            },
1357            values,
1358        )
1359    }
1360
1361    /// For a group made with [`Self::parallel`] or [`Self::stagger`]:
1362    /// whether one of its animations stopped stops the others (by
1363    /// default it does). Other animations stay as they are.
1364    pub fn stop_together(self, stop_together: bool) -> Self {
1365        let (mut spec, values) = self.into_parts();
1366        if let Composite::Parallel {
1367            stop_together: s, ..
1368        } = &mut spec
1369        {
1370            *s = stop_together;
1371        }
1372        Self::new(spec, values)
1373    }
1374
1375    /// For a loop made with [`Self::looped`]: whether its values go back
1376    /// to where they were before each run (by default they do). Other
1377    /// animations stay as they are.
1378    pub fn reset_before_iteration(self, reset: bool) -> Self {
1379        let (mut spec, values) = self.into_parts();
1380        if let Composite::Loop { reset: r, .. } = &mut spec {
1381            *r = reset;
1382        }
1383        Self::new(spec, values)
1384    }
1385
1386    /// Runs it, stopping a run of it going on (which ends `false`). It
1387    /// runs either way: await the end in a task to follow it up, or drop
1388    /// it. An animation of no values (only delays) has nothing to run on
1389    /// and ends at once.
1390    pub fn start(&self) -> AnimationEnd {
1391        let (end, slot) = Answer::new();
1392        let run = &self.0.run;
1393        let Some(executor) = run.executor.upgrade() else {
1394            if self.0.values.is_empty() {
1395                slot.borrow_mut().deliver(true);
1396            }
1397            return AnimationEnd(end);
1398        };
1399        self.stop();
1400        if run.key.get() == 0 {
1401            run.key.set(executor.next_animation_id());
1402        }
1403        let animation = executor.next_animation_id();
1404        run.animation.set(animation);
1405        executor.act(Action::Animate {
1406            op: AnimationOp::StartComposite {
1407                animation,
1408                key: run.key.get(),
1409                spec: self.0.spec.clone(),
1410            },
1411            animation,
1412            end: slot,
1413        });
1414        AnimationEnd(end)
1415    }
1416
1417    /// Stops its run where it is (the run ends `false`).
1418    pub fn stop(&self) {
1419        let run = &self.0.run;
1420        let animation = run.animation.replace(0);
1421        if animation != 0
1422            && let Some(executor) = run.executor.upgrade()
1423        {
1424            executor.act(Action::Animation(AnimationOp::StopAnimation { animation }));
1425        }
1426    }
1427
1428    /// Stops its run (which ends `false`) and puts its values back where
1429    /// they were when it last started.
1430    pub fn reset(&self) {
1431        let run = &self.0.run;
1432        run.animation.set(0);
1433        let key = run.key.get();
1434        if key != 0
1435            && let Some(executor) = run.executor.upgrade()
1436        {
1437            executor.act(Action::Animation(AnimationOp::ResetComposite { key }));
1438        }
1439    }
1440}
1441
1442impl fmt::Debug for Animation {
1443    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1444        f.debug_tuple("Animation").field(&self.0.spec).finish()
1445    }
1446}
1447
1448/// Animated values for a view's opacity and the parts of its transform
1449/// (TS: `createMotion`), and motions to play on them: presets
1450/// ([`crate::animation::MotionPreset`]: entrances, exits, attention seekers,
1451/// loops) or keyframes of the app's own ([`MotionSpec`]). Bind it with
1452/// [`super::Styled::bind_motion`]. A `Copy` handle, kept by the owner
1453/// current when it is made, as an [`AnimatedValue`] is.
1454///
1455/// ```ignore
1456/// let card = motion().entering(MotionPreset::FadeInUp);
1457/// view().bind_motion(&card).on_press(move || {
1458///     card.play(MotionPreset::Pulse);
1459/// })
1460/// ```
1461#[derive(Clone, Copy)]
1462pub struct Motion {
1463    values: [AnimatedValue; 9],
1464}
1465
1466impl fmt::Debug for Motion {
1467    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1468        f.debug_struct("Motion").finish_non_exhaustive()
1469    }
1470}
1471
1472impl Motion {
1473    pub(crate) fn new(executor: &Rc<Executor>) -> Self {
1474        Self {
1475            values: MotionChannel::ALL.map(|c| AnimatedValue::new(executor, c.identity())),
1476        }
1477    }
1478
1479    /// The value of `channel` (opacity 0..1, translations in points,
1480    /// rotations in degrees, scales).
1481    pub fn value(&self, channel: MotionChannel) -> AnimatedValue {
1482        self.values[channel.index()]
1483    }
1484
1485    /// Starting where `motion` starts and playing it at once: a view that
1486    /// comes in shows its first frame where the motion begins.
1487    pub fn entering(self, motion: impl Into<MotionSpec>) -> Self {
1488        let motion = motion.into();
1489        for (channel, start) in motion.start_values() {
1490            self.value(channel).set(start);
1491        }
1492        let _ = self.play(motion);
1493        self
1494    }
1495
1496    /// Plays `motion` on its channels (a new one interrupts the one
1497    /// playing). When the user asks for less motion
1498    /// ([`super::reduce_motion`]), it lands where it ends without moving.
1499    pub fn play(&self, motion: impl Into<MotionSpec>) -> AnimationEnd {
1500        self.run(motion.into(), super::reduce_motion())
1501    }
1502
1503    /// Plays `motion` even when the user asks for less motion.
1504    pub fn play_ignoring_reduce_motion(&self, motion: impl Into<MotionSpec>) -> AnimationEnd {
1505        self.run(motion.into(), false)
1506    }
1507
1508    /// `motion` as an [`Animation`] to compose, not started (TS:
1509    /// `motion.animation(..)`): `Animation::stagger_from(60.0,
1510    /// StaggerFrom::Center, cards.iter().map(|m| m.animation(..)))`. Like
1511    /// [`Self::play`], it lands at its end when the user asks for less
1512    /// motion (as things are when it is made).
1513    pub fn animation(&self, motion: impl Into<MotionSpec>) -> Animation {
1514        self.composed(motion.into(), super::reduce_motion())
1515    }
1516
1517    fn composed(&self, motion: MotionSpec, reduced: bool) -> Animation {
1518        let nodes = self.values.map(|v| v.0.id());
1519        let held = self
1520            .values
1521            .iter()
1522            .filter_map(|v| v.0.live())
1523            .collect::<Vec<_>>();
1524        Animation::new(motion.composite(&nodes, reduced), held)
1525    }
1526
1527    fn run(&self, motion: MotionSpec, reduced: bool) -> AnimationEnd {
1528        self.composed(motion, reduced).start()
1529    }
1530
1531    /// Stops it where it is.
1532    pub fn stop(&self) {
1533        for value in &self.values {
1534            value.stop();
1535        }
1536    }
1537
1538    /// Stops it and puts every channel back at rest.
1539    pub fn reset(&self) {
1540        for channel in MotionChannel::ALL {
1541            self.value(channel).set(channel.identity());
1542        }
1543    }
1544}
1545
1546/// A timing a component's prop takes (TS `{ duration?: number; easing?:
1547/// Easing; delay?: number; frameRate?: number }`): the options of
1548/// `AnimatedValue.timing` in `nsh/animated`, with its defaults (300 ms,
1549/// ease in-out, no delay, the screen's highest rate).
1550impl super::JsValue for Timing {
1551    fn ts_type(_types: &mut super::TsTypes) -> String {
1552        "{ duration?: number; easing?: import(\"nsh\").Easing; delay?: number; frameRate?: number }"
1553            .into()
1554    }
1555
1556    fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
1557        let json = value.to_json()?;
1558        let Some(object) = json.as_object() else {
1559            return Err(value.expected("a timing: `{ duration, easing, delay }`"));
1560        };
1561        let num = |key: &str| object.get(key).and_then(|v| v.as_f64()).map(|v| v as f32);
1562        let default = Timing::default();
1563        Ok(Timing {
1564            duration_ms: num("duration").unwrap_or(default.duration_ms).max(0.0),
1565            easing: object
1566                .get("easing")
1567                .and_then(|e| crate::js::animation::easing(&JsonInput(Some(e))))
1568                .unwrap_or(default.easing),
1569            delay_ms: num("delay").unwrap_or(default.delay_ms).max(0.0),
1570            frame_rate: crate::style::frame_rate(num("frameRate")),
1571        })
1572    }
1573
1574    fn to_js<'a>(
1575        &self,
1576        host: &'a dyn super::JsHost,
1577    ) -> Result<super::JsOwned<'a>, super::PropError> {
1578        let mut json = serde_json::json!({ "duration": self.duration_ms, "delay": self.delay_ms });
1579        if let Some(hz) = self.frame_rate {
1580            json["frameRate"] = hz.into();
1581        }
1582        Ok(super::JsOwned::new(host, host.json(&json)?))
1583    }
1584}
1585
1586/// A spring a component's prop takes (TS `{ stiffness?: number; damping?:
1587/// number; mass?: number; velocity?: number; frameRate?: number }`): the
1588/// options of `AnimatedValue.spring` in `nsh/animated`, with its defaults.
1589impl super::JsValue for Spring {
1590    fn ts_type(_types: &mut super::TsTypes) -> String {
1591        "{ stiffness?: number; damping?: number; mass?: number; velocity?: number; frameRate?: number }"
1592            .into()
1593    }
1594
1595    fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
1596        let json = value.to_json()?;
1597        let Some(object) = json.as_object() else {
1598            return Err(value.expected("a spring: `{ stiffness, damping, mass }`"));
1599        };
1600        let num = |key: &str| object.get(key).and_then(|v| v.as_f64()).map(|v| v as f32);
1601        let default = Spring::default();
1602        Ok(Spring {
1603            stiffness: num("stiffness").unwrap_or(default.stiffness),
1604            damping: num("damping").unwrap_or(default.damping),
1605            mass: num("mass").unwrap_or(default.mass),
1606            velocity: num("velocity"),
1607            frame_rate: crate::style::frame_rate(num("frameRate")),
1608        })
1609    }
1610
1611    fn to_js<'a>(
1612        &self,
1613        host: &'a dyn super::JsHost,
1614    ) -> Result<super::JsOwned<'a>, super::PropError> {
1615        let mut json = serde_json::json!({
1616            "stiffness": self.stiffness,
1617            "damping": self.damping,
1618            "mass": self.mass,
1619        });
1620        if let Some(hz) = self.frame_rate {
1621            json["frameRate"] = hz.into();
1622        }
1623        Ok(super::JsOwned::new(host, host.json(&json)?))
1624    }
1625}
1626
1627/// A JSON value as the core's decoders read JS values (an easing, an
1628/// image source).
1629pub(crate) struct JsonInput<'a>(pub(crate) Option<&'a crate::JsonValue>);
1630
1631/// A JSON array, read by index.
1632pub(crate) struct JsonList<'a>(&'a [crate::JsonValue]);
1633
1634impl<'a> crate::js::host::HostList for JsonList<'a> {
1635    type Item = JsonInput<'a>;
1636
1637    fn len(&self) -> usize {
1638        self.0.len()
1639    }
1640
1641    fn item(&self, index: usize) -> Option<JsonInput<'a>> {
1642        self.0.get(index).map(|v| JsonInput(Some(v)))
1643    }
1644}
1645
1646impl<'a> crate::js::host::HostInput for JsonInput<'a> {
1647    type List = JsonList<'a>;
1648
1649    fn is_nullish(&self) -> bool {
1650        self.0.is_none_or(|v| v.is_null())
1651    }
1652
1653    fn is_object(&self) -> bool {
1654        self.0.is_some_and(|v| v.is_object() || v.is_array())
1655    }
1656
1657    fn as_bool(&self) -> Option<bool> {
1658        self.0?.as_bool()
1659    }
1660
1661    fn as_number(&self) -> Option<f64> {
1662        self.0?.as_f64()
1663    }
1664
1665    fn as_string(&self) -> Option<String> {
1666        self.0?.as_str().map(str::to_owned)
1667    }
1668
1669    fn field(&self, key: &str) -> Option<Self> {
1670        self.0?.get(key).map(|v| JsonInput(Some(v)))
1671    }
1672
1673    fn as_list(&self) -> Option<JsonList<'a>> {
1674        self.0?.as_array().map(|a| JsonList(a))
1675    }
1676
1677    fn entries(&self) -> Vec<(String, Self)> {
1678        match self.0.and_then(|v| v.as_object()) {
1679            Some(o) => o
1680                .iter()
1681                .map(|(k, v)| (k.clone(), JsonInput(Some(v))))
1682                .collect(),
1683            None => Vec::new(),
1684        }
1685    }
1686
1687    fn truthy(&self) -> bool {
1688        match self.0 {
1689            None | Some(crate::JsonValue::Null) => false,
1690            Some(crate::JsonValue::Bool(b)) => *b,
1691            Some(crate::JsonValue::Number(n)) => n.as_f64().is_some_and(|n| n != 0.0),
1692            Some(crate::JsonValue::String(s)) => !s.is_empty(),
1693            Some(_) => true,
1694        }
1695    }
1696}
1697
1698#[cfg(test)]
1699mod tests {
1700    use super::*;
1701    use crate::element::reactive::{Runtime, create_root};
1702
1703    fn released(executor: &Executor) -> usize {
1704        executor
1705            .take_actions()
1706            .into_iter()
1707            .filter(|a| matches!(a, Action::Animation(AnimationOp::Release { .. })))
1708            .count()
1709    }
1710
1711    #[test]
1712    fn a_derived_chain_keeps_its_middle_nodes() {
1713        let runtime = Runtime::default();
1714        let _entered = runtime.enter();
1715        let executor = Rc::new(Executor::default());
1716        let (value_owner, v) = create_root(|| AnimatedValue::new(&executor, 0.5));
1717        // The chain's handles go with their owner; a binding of its end
1718        // holds the product too.
1719        let (chain_owner, end) = create_root(|| v.node().mul(2.0).sub(1.0));
1720        let bound = end.live().expect("live");
1721        chain_owner.dispose();
1722        assert_eq!(released(&executor), 0, "the product lives with the end");
1723        assert!(end.live().is_none(), "its handle is gone");
1724        drop(bound);
1725        assert_eq!(released(&executor), 2, "then both go");
1726        value_owner.dispose();
1727        assert_eq!(released(&executor), 1);
1728    }
1729
1730    #[test]
1731    fn copies_are_the_same_value_in_every_closure() {
1732        let runtime = Runtime::default();
1733        let _entered = runtime.enter();
1734        let executor = Rc::new(Executor::default());
1735        let (_owner, v) = create_root(|| AnimatedValue::new(&executor, 0.0));
1736        let node = v.node().id();
1737        let _ = ops(&executor);
1738        // Two closures and the code after them use the one value.
1739        let press = move || v.set(1.0);
1740        let release = move || v.set_offset(2.0);
1741        press();
1742        release();
1743        let _ = v.timing(3.0, 100.0, Easing::Linear);
1744        assert!(matches!(
1745            &ops(&executor)[..],
1746            [
1747                AnimationOp::Set { node: a, value: 1.0 },
1748                AnimationOp::SetOffset { node: b, offset: 2.0 },
1749                AnimationOp::Start { node: c, .. },
1750            ] if [*a, *b, *c] == [node; 3]
1751        ));
1752        let copy = v;
1753        assert_eq!(copy, v);
1754        assert_eq!(
1755            format!("{v:?}"),
1756            format!("AnimatedValue(AnimatedNode({node}))")
1757        );
1758    }
1759
1760    #[test]
1761    fn handles_do_nothing_once_their_owner_is_gone() {
1762        let runtime = Runtime::default();
1763        let _entered = runtime.enter();
1764        let executor = Rc::new(Executor::default());
1765        let (owner, (v, half)) = create_root(|| {
1766            let v = AnimatedValue::new(&executor, 0.0);
1767            (v, v.mul(0.5))
1768        });
1769        let jump = Animation::timing(&v, 1.0, Timing::default());
1770        let _ = ops(&executor);
1771        owner.dispose();
1772        // The value and its product go with their owner; the composite
1773        // holds the value's node while it lives.
1774        assert_eq!(ops(&executor), [AnimationOp::Release { node: half.id() }]);
1775        drop(jump);
1776        assert_eq!(
1777            ops(&executor),
1778            [AnimationOp::Release {
1779                node: v.node().id()
1780            }]
1781        );
1782
1783        v.set(1.0);
1784        v.stop();
1785        v.set_offset(1.0);
1786        v.flatten_offset();
1787        v.extract_offset();
1788        let ended = v.spring(1.0, Spring::default());
1789        let tasks = tokio::runtime::Builder::new_current_thread()
1790            .build()
1791            .unwrap();
1792        assert!(!tasks.block_on(ended.into_future()), "unfinished, at once");
1793        drop(v.value());
1794        let derived = [
1795            v.interpolate(&[0.0, 1.0], &[0.0, 1.0]),
1796            v.add(&half),
1797            half.mul(2.0),
1798        ];
1799        assert!(derived.iter().all(|n| n.live().is_none()));
1800        drop(Animation::timing(&v, 1.0, Timing::default()).start());
1801        assert_eq!(ops(&executor), [], "nothing reaches the graph");
1802        // Handles keep their identity.
1803        let copy = half;
1804        assert_eq!(copy, half);
1805        assert_eq!(format!("{half:?}"), format!("AnimatedNode({})", half.id()));
1806    }
1807
1808    #[test]
1809    fn deriving_again_finds_the_node_among_many() {
1810        let runtime = Runtime::default();
1811        let _entered = runtime.enter();
1812        let executor = Rc::new(Executor::default());
1813        let (_owner, (v, first, again, zeros)) = create_root(|| {
1814            let v = AnimatedValue::new(&executor, 0.0);
1815            let derive = || -> Vec<AnimatedNode> {
1816                (0..2_000)
1817                    .map(|i| v.interpolate(&[0.0, 1.0], &[0.0, i as f32]))
1818                    .collect()
1819            };
1820            let first = derive();
1821            let again = derive();
1822            // Zeros of either sign are one number: one node.
1823            let zeros = [
1824                v.interpolate(&[0.0, 1.0], &[0.0, 1.0]),
1825                v.interpolate(&[-0.0, 1.0], &[-0.0, 1.0]),
1826            ];
1827            (v, first, again, zeros)
1828        });
1829        assert!(first.iter().zip(&again).all(|(a, b)| a == b));
1830        let mut ids: Vec<_> = first.iter().map(AnimatedNode::id).collect();
1831        ids.dedup();
1832        assert_eq!(ids.len(), 2_000, "distinct keys, distinct nodes");
1833        assert_eq!(zeros[0], zeros[1]);
1834        assert_eq!(zeros[0], first[1]);
1835        let _ = v;
1836    }
1837
1838    #[test]
1839    fn dead_derived_nodes_are_neither_found_nor_kept() {
1840        let runtime = Runtime::default();
1841        let _entered = runtime.enter();
1842        let executor = Rc::new(Executor::default());
1843        let (_value_owner, v) = create_root(|| AnimatedValue::new(&executor, 0.0));
1844        let (owner, gone) = create_root(|| v.interpolate(&[0.0, 1.0], &[2.0, 3.0]));
1845        let id = gone.id();
1846        owner.dispose();
1847        let (_owner, made) = create_root(|| v.interpolate(&[0.0, 1.0], &[2.0, 3.0]));
1848        assert_ne!(made.id(), id, "a dead node is made again");
1849        // Nodes made and dropped over and over are swept out as they go.
1850        for round in 0..50 {
1851            let (owner, _) = create_root(|| {
1852                (0..200)
1853                    .map(|i| v.interpolate(&[0.0, 1.0], &[round as f32, i as f32]))
1854                    .collect::<Vec<_>>()
1855            });
1856            owner.dispose();
1857        }
1858        let kept: usize = executor.derived().by_hash.values().map(Vec::len).sum();
1859        assert!(kept <= 2 * 200 + 64, "{kept} kept");
1860    }
1861
1862    /// Deriving many distinct nodes, one by one, as a player's scene does:
1863    /// `cargo test --release -p nsh-core bench_derive -- --ignored
1864    /// --nocapture`.
1865    #[test]
1866    #[ignore = "benchmark"]
1867    fn bench_derive_many_nodes() {
1868        let runtime = Runtime::default();
1869        let _entered = runtime.enter();
1870        let executor = Rc::new(Executor::default());
1871        for n in [5_000, 20_000] {
1872            let start = std::time::Instant::now();
1873            let (owner, _nodes) = create_root(|| {
1874                let v = AnimatedValue::new(&executor, 0.0);
1875                (0..n)
1876                    .map(|i| v.interpolate(&[0.0, 0.5, 1.0], &[0.0, i as f32, 1.0]))
1877                    .collect::<Vec<_>>()
1878            });
1879            println!("{n} derived nodes: {:?}", start.elapsed());
1880            owner.dispose();
1881            let _ = executor.take_actions();
1882        }
1883    }
1884
1885    /// The graph operations `executor` was asked for (animations' ends
1886    /// dropped).
1887    fn ops(executor: &Executor) -> Vec<AnimationOp> {
1888        executor
1889            .take_actions()
1890            .into_iter()
1891            .filter_map(|a| match a {
1892                Action::Animation(op) | Action::Animate { op, .. } => Some(op),
1893                _ => None,
1894            })
1895            .collect()
1896    }
1897
1898    fn timing(to: f32, ms: f32) -> Driver {
1899        Timing::new(ms, Easing::Linear).driver(to)
1900    }
1901
1902    #[test]
1903    fn keyframes_staggers_and_motions_describe_their_trees() {
1904        use crate::animation::{MotionPreset, StaggerFrom};
1905        let runtime = Runtime::default();
1906        let _entered = runtime.enter();
1907        let executor = Rc::new(Executor::default());
1908        let values: Vec<AnimatedValue> =
1909            (0..3).map(|_| AnimatedValue::new(&executor, 0.0)).collect();
1910        let step = |v: &AnimatedValue| {
1911            Animation::keyframes(
1912                v,
1913                [Keyframe::new(0.0), Keyframe::new(1.0)],
1914                KeyframeTiming::new(100.0),
1915            )
1916        };
1917        let rippled = Animation::stagger_from(40.0, StaggerFrom::Center, values.iter().map(step));
1918        let Composite::Parallel { children, .. } = &rippled.0.spec else {
1919            panic!("{:?}", rippled.0.spec)
1920        };
1921        let delays: Vec<f32> = children
1922            .iter()
1923            .map(|c| match c {
1924                Composite::Sequence(s) => match s[0] {
1925                    Composite::Delay(ms) => ms,
1926                    _ => -1.0,
1927                },
1928                _ => -1.0,
1929            })
1930            .collect();
1931        assert_eq!(delays, [40.0, 0.0, 40.0]);
1932
1933        let motion = Motion::new(&executor);
1934        executor.take_actions();
1935        let _ = motion.play_ignoring_reduce_motion(MotionPreset::Shake);
1936        let started = executor.take_actions().into_iter().find_map(|a| match a {
1937            Action::Animate {
1938                op: AnimationOp::StartComposite { spec, .. },
1939                ..
1940            } => Some(spec),
1941            _ => None,
1942        });
1943        let Some(Composite::Parallel { children, .. }) = started else {
1944            panic!("{started:?}")
1945        };
1946        // `shake` moves one channel: translateX.
1947        assert_eq!(children.len(), 1);
1948        let mut nodes = Vec::new();
1949        children[0].nodes(&mut nodes);
1950        assert_eq!(nodes, [motion.value(MotionChannel::TranslateX).node().id()]);
1951    }
1952
1953    #[test]
1954    fn composites_describe_their_steps() {
1955        let runtime = Runtime::default();
1956        let _entered = runtime.enter();
1957        let executor = Rc::new(Executor::default());
1958        let (a, b) = (
1959            AnimatedValue::new(&executor, 0.0),
1960            AnimatedValue::new(&executor, 1.0),
1961        );
1962        let (na, nb) = (a.node().id(), b.node().id());
1963        let run = |node, to| Composite::Run {
1964            node,
1965            driver: timing(to, 100.0),
1966        };
1967        let step =
1968            |v: &AnimatedValue, to| Animation::timing(v, to, Timing::new(100.0, Easing::Linear));
1969        let staggered = Animation::stagger(50.0, [step(&a, 1.0), step(&b, 2.0)]);
1970        let delayed = |ms, c| Composite::Sequence(vec![Composite::Delay(ms), c]);
1971        assert_eq!(
1972            staggered.0.spec,
1973            Composite::Parallel {
1974                children: vec![delayed(0.0, run(na, 1.0)), delayed(50.0, run(nb, 2.0))],
1975                stop_together: true,
1976            }
1977        );
1978        let ids = |a: &Animation| a.0.values.iter().map(LiveNode::id).collect::<Vec<_>>();
1979        assert_eq!(ids(&staggered), [na, nb]);
1980
1981        let looped = Animation::sequence([step(&a, 1.0), Animation::delay(10.0), step(&a, 0.0)])
1982            .looped(Some(3))
1983            .reset_before_iteration(false);
1984        assert_eq!(
1985            looped.0.spec,
1986            Composite::Loop {
1987                child: Box::new(Composite::Sequence(vec![
1988                    run(na, 1.0),
1989                    Composite::Delay(10.0),
1990                    run(na, 0.0)
1991                ])),
1992                iterations: Some(3),
1993                reset: false,
1994            }
1995        );
1996        // Each value once.
1997        assert_eq!(ids(&looped), [na]);
1998        let apart = Animation::parallel([step(&a, 1.0)]).stop_together(false);
1999        assert!(matches!(
2000            apart.0.spec,
2001            Composite::Parallel {
2002                stop_together: false,
2003                ..
2004            }
2005        ));
2006        // A delay on its own driver.
2007        let delayed = Animation::timing(
2008            &a,
2009            1.0,
2010            Timing {
2011                delay_ms: 40.0,
2012                ..Timing::default()
2013            },
2014        );
2015        assert!(matches!(
2016            delayed.0.spec,
2017            Composite::Run {
2018                driver: Driver::Timing {
2019                    delay_ms: 40.0,
2020                    duration_ms: 300.0,
2021                    easing: Easing::EaseInOut,
2022                    ..
2023                },
2024                ..
2025            }
2026        ));
2027    }
2028
2029    #[test]
2030    fn composites_start_stop_reset_and_release_by_key() {
2031        let runtime = Runtime::default();
2032        let _entered = runtime.enter();
2033        let executor = Rc::new(Executor::default());
2034        let x = AnimatedValue::new(&executor, 0.0);
2035        let _ = ops(&executor);
2036        let jump = Animation::sequence([
2037            Animation::timing(&x, 10.0, Timing::default()),
2038            Animation::spring(&x, 0.0, Spring::default()),
2039        ]);
2040        // Nothing until it runs.
2041        jump.stop();
2042        jump.reset();
2043        assert_eq!(ops(&executor), []);
2044
2045        let _ = jump.start();
2046        let [
2047            AnimationOp::StartComposite {
2048                animation,
2049                key,
2050                spec,
2051            },
2052        ] = &ops(&executor)[..]
2053        else {
2054            panic!("a composite start");
2055        };
2056        assert_eq!((animation % 2, key % 2), (1, 1), "the core's ids are odd");
2057        assert_eq!(spec, &jump.0.spec);
2058        let (first, key) = (*animation, *key);
2059
2060        // Again: the run going on stops first; the key stays.
2061        let _ = jump.clone().start();
2062        let again = ops(&executor);
2063        assert!(matches!(
2064            &again[..],
2065            [
2066                AnimationOp::StopAnimation { animation: a },
2067                AnimationOp::StartComposite { animation: b, key: k, .. },
2068            ] if *a == first && *b != first && *k == key
2069        ));
2070        jump.stop();
2071        assert!(matches!(
2072            &ops(&executor)[..],
2073            [AnimationOp::StopAnimation { .. }]
2074        ));
2075        jump.stop();
2076        assert_eq!(ops(&executor), [], "stopped once");
2077        jump.reset();
2078        assert_eq!(ops(&executor), [AnimationOp::ResetComposite { key }]);
2079
2080        drop(jump);
2081        assert_eq!(ops(&executor), [AnimationOp::ReleaseComposite { key }]);
2082    }
2083
2084    #[test]
2085    fn delays_alone_end_at_once() {
2086        let runtime = tokio::runtime::Builder::new_current_thread()
2087            .build()
2088            .unwrap();
2089        let end = Animation::sequence([Animation::delay(100.0)]).start();
2090        assert!(runtime.block_on(end.into_future()));
2091    }
2092
2093    #[test]
2094    fn values_derive_like_their_nodes() {
2095        let runtime = Runtime::default();
2096        let _entered = runtime.enter();
2097        let executor = Rc::new(Executor::default());
2098        let t = AnimatedValue::new(&executor, 0.0);
2099        let right = Interpolation {
2100            extrapolate_right: Extrapolate::Extend,
2101            ..Interpolation::default()
2102        };
2103        let angle = t.interpolate_with(&[0.0, 1.0], Output::Numbers(vec![0.0, 180.0]), right);
2104        let [
2105            ..,
2106            AnimationOp::CreateInterpolate {
2107                extrapolate_left,
2108                extrapolate_right,
2109                easing,
2110                ..
2111            },
2112        ] = &ops(&executor)[..]
2113        else {
2114            panic!("an interpolation");
2115        };
2116        assert_eq!(
2117            (*extrapolate_left, *extrapolate_right, *easing),
2118            (Extrapolate::Clamp, Extrapolate::Extend, Easing::Linear)
2119        );
2120        // The same node as through `node()`.
2121        assert_eq!(
2122            angle,
2123            t.node()
2124                .interpolate_with(&[0.0, 1.0], Output::Numbers(vec![0.0, 180.0]), right)
2125        );
2126        assert_eq!(t.diff_clamp(0.0, 44.0), t.node().diff_clamp(0.0, 44.0));
2127        assert_eq!(t.mul(-1.0), t.node().mul(-1.0));
2128    }
2129
2130    #[test]
2131    fn curves_sample_as_the_graph_runs_them() {
2132        // A spring from 0 to 1, one value a frame at 60 Hz, at rest at its
2133        // end; at 120 Hz about twice the frames.
2134        let spring = sample_spring(0.0, 1.0, Spring::default(), 60.0);
2135        assert_eq!(spring[0], 0.0);
2136        assert!((spring.last().unwrap() - 1.0).abs() < 1e-3, "{spring:?}");
2137        let fast = sample_spring(0.0, 1.0, Spring::default(), 120.0);
2138        assert!(fast.len() > spring.len() * 3 / 2, "{}", fast.len());
2139        // A spring that never rests stops at the cap.
2140        let undamped = Spring {
2141            damping: 0.0,
2142            ..Spring::default()
2143        };
2144        assert_eq!(
2145            sample_spring(0.0, 1.0, undamped, 60.0).len(),
2146            crate::animation::MAX_SAMPLES
2147        );
2148        // A fling glides on and slows down; within bounds it stops at one.
2149        let decay = sample_decay(0.0, 1000.0, 0.998, 60.0);
2150        assert!(decay.windows(2).all(|w| w[1] >= w[0]), "{decay:?}");
2151        assert!(*decay.last().unwrap() > 400.0, "{decay:?}");
2152        let within = sample_decay_within(0.0, 1000.0, 0.998, (0.0, 100.0), 0.0, 60.0);
2153        assert!(within.iter().all(|&x| (0.0..=100.0).contains(&x)));
2154        assert_eq!(*within.last().unwrap(), 100.0);
2155        // An easing's curve: both ends.
2156        let curve = super::super::sample_easing(Easing::EaseInOut, 5);
2157        assert_eq!((curve[0], curve[4], curve.len()), (0.0, 1.0, 5));
2158    }
2159}